1.JVM为每个加载的class及interface创建了对应的Class实例来保存class及interface的所有信息;
获取一个class对应的Class实例后,就可以获取该class的所有信息;
通过Class实例获取class信息的方法称为反射(Reflection);
JVM总是动态加载class,可以在运行期根据条件来控制加载class。
2.Java的反射API主要用于在运行过程中动态生成类、接口或对象等信息,其常用API如下。
public class ReflectTest {
public static void main(String[] args) {
Class class1 = String.class;
printClassInfo(class1);
Class cls2 = "hello".getClass();
printClassInfo(cls2);
Class cls3 = String[].class;
printClassInfo(cls3);
//true,指向同一个实例
System.out.println("class1 == cls2? "+(class1 == cls2));
}
private static void printClassInfo(Class c) {
System.out.println("getName()=" + c.getName());
System.out.println("getSimpleName()=" + c.getSimpleName());
System.out.println("isInterface()=" + c.isInterface());
System.out.println("isEnum()=" + c.isEnum());
System.out.println("isArray()=" + c.isArray());
System.out.println("isPrimitive=" + c.isPrimitive());
}
}
3.Class类提供了以下几个方法来获取字段:
class Student extends Person {
public int score;
private int grade;
}
class Person {
public String name;
}
首先尝试访问共有和私有变量:
private static void method() throws NoSuchFieldException {
Class cls = Student.class;
System.out.println(cls.getField("score"));
System.out.println(cls.getDeclaredField("score"));
//获取私有方法报错
// System.out.println(cls.getField("grade"));
System.out.println(cls.getDeclaredField("grade"));
}
使用setAccessible,访问私有成员变量:
private static void privateField() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {
Class cls = Class.forName("com.cathyjava.j2se.reflect.Student");
Student student = (Student) cls.getDeclaredConstructor().newInstance();
Field field = cls.getDeclaredField("grade");
field.setAccessible(true);
field.set(student, 2);
}
原文:https://www.cnblogs.com/janes/p/14603333.html