1.简介
能够动态获取对象的所有信息以及调用对象方法的功能称之为反射。
2.使用案例
public class Student {
private String name;
int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
System.out.println("constructor params run with name:"+this.name+",age:"+this.age);
}
public Student() {
System.out.println("constructor run without params");
}
public void show(){
System.out.println("public show run");
}
private void show1(){
System.out.println("private show run");
}
public void fun(String str){
System.out.println("fun run");
}
public static void staticMethod(){
System.out.println("staticMethod run");
}
}
3.获取类对象
Class clazz = Class.forName("Student");
4.获取构造函数
- 无参数
Class clazz = Class.forName("Student");
clazz.newInstance();
- 含参数
Class clazz = Class.forName("Student");
Constructor constructor = clazz.getDeclaredConstructor(String.class,int.class);
constructor.newInstance("steven",28);
5.获取属性
- 无参数
Class clazz = Class.forName("Student");
Student student = (Student) clazz.newInstance();
Field field = clazz.getDeclaredField("name");
field.setAccessible(true);
field.set(student,"steven");
System.out.println(field.get(student));
- 含参数
Class clazz = Class.forName("Student");
Constructor constructor = clazz.getDeclaredConstructor(String.class,int.class);
Student student = (Student) constructor.newInstance("steven",28);
Field field = clazz.getDeclaredField("name");
field.setAccessible(true);
field.set(student,"tom");
System.out.println(field.get(student));
6.获取方法
- 无参数
Class clazz = Class.forName("Student");
Student student = (Student) clazz.newInstance();
Method method = clazz.getDeclaredMethod("show");
method.invoke(student);
- 含参数
Class clazz = Class.forName("Student");
Constructor constructor = clazz.getDeclaredConstructor(String.class,int.class);
Student student = (Student) constructor.newInstance("steven",28);
Method method = clazz.getDeclaredMethod("fun",String.class);
method.invoke(student,"hello fun");