反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法和属性;这种动态获取的信息以及动态调用对象的方法的功能称为java语言的反射机制。
1.通过对象获取完整的包名和类名
package com.qhong; public class Main { public static void main(String[] args) { TestReflect testReflect = new TestReflect(); System.out.println(testReflect.getClass().getName()); } } class TestReflect {}
com.qhong.TestReflect
实例化class的对象
package com.qhong; public class Main { public static void main (String[] args) throws Exception{ Class<?> class1 = null; Class<?> class2 = null; Class<?> class3 = null; // 一般采用这种形式 class1 = Class.forName("com.qhong.TestReflect"); class2 = new TestReflect().getClass(); class3 = TestReflect.class; System.out.println("类名称 " + class1.getName()); System.out.println("类名称 " + class2.getName()); System.out.println("类名称 " + class3.getName()); } } class TestReflect {}
类名称 com.qhong.TestReflect
类名称 com.qhong.TestReflect
类名称 com.qhong.TestReflect
获取一个对象的父类已经继承的接口
package com.qhong; import java.io.Serializable; public class Main { public static void main (String[] args) throws Exception{ Class<?> cla= Class.forName("com.qhong.TestReflect"); // 取得父类 Class<?> parentClass = cla.getSuperclass(); System.out.println("cla的父类为:" + parentClass.getName()); // 获取所有的接口 Class<?> interfaces[] = cla.getInterfaces(); System.out.println("cla实现的接口有:"); for (int i = 0; i < interfaces.length; i++) { System.out.println((i + 1) + ":" + interfaces[i].getName()); } } } class TestReflect implements Serializable {}
cla的父类为:java.lang.Object
cla实现的接口有:
1:java.io.Serializable
http://www.cnblogs.com/lzq198754/p/5780331.html
原文:http://www.cnblogs.com/hongdada/p/6240907.html