@Data
public class Student {
private int age;
}
public class Reflection {
public static void main(String[] args) throws Exception {
// 正常调用
Student student = new Student();
student.setAge(18);
System.out.println(student.getAge());
// Reflection
Class studentClass = Class.forName("com.git.Reflection.Student");
// get method
Method setAge = studentClass.getMethod("setAge", int.class);
Method getAge = studentClass.getMethod("getAge");
// Constructor
Constructor studentClassConstructor = studentClass.getConstructor();
// new 一个 Object
Object o = studentClassConstructor.newInstance();
setAge.invoke(o, 18);
Object age = getAge.invoke(o);
System.out.println(age);
}
}
执行结果完全是一样的,区别就在,
第一段在代码未执行的时就已经确定了要运行的类(Student)
第二段代码则是在运行的时候通过类的全类名确定要运行的类 (Student)
故反射
就是在代码运行的时候才确定需要执行的类并且可以拿到其所有的方法
Class
对象Class.forName
需要类的全类名
Class studentClass = Class.forName("com.java.Reflection.Student");
Object.class
Class<Student> studentClass = Student.class;
Object.getClass()
类对象的 getClass() 方法
String s = new String("qqq");
Class<? extends String> aClass1 = s.getClass();
Class
对象的 newInstance()
方法Class<Student> aClass = Student.class;
Student student = constructor.newInstance();
Constructor
的newInstance()
方法Class<Student> studentClass = Student.class;
Constructor<Student> constructor = studentClass.getConstructor();
Student student = constructor.newInstance();
非私有属性
Class studentClass = Student.class;
Field[] fields = studentClass.getFields();
Constructor constructor = studentClass.getConstructor();
System.out.println(constructor.toString());
for (Field field : fields) {
System.out.println(field.getName());
}
输出结果
public com.java.Reflection.Student()
没有输出属性,原因是 Student
就没有非私有的属性,获取私有的属性需要用到关键字 declared
全部属性
Class studentClass = Student.class;
Field[] fields = studentClass.getDeclaredFields();
Constructor declaredConstructor = studentClass.getDeclaredConstructor();
System.out.println(declaredConstructor.toString());
for (Field field : fields) {
System.out.println(field.getName());
}
输出结果
public com.ali.Reflection.Student()
age
Java 反射机制 ( Java Reflection Mechanism )
原文:https://www.cnblogs.com/hellojava404/p/13701059.html