一、概述
当在程序运行期间,对于任意一个类,都能够知道这个类的所有属性与方法,对于任意一个对象,都能够调用它的任意一个属性与方法,这种动态获取信息与动态调用对象的方法的机制就是反射机制。当然,前提条件是必须拿到类的.class对象。至于这个class对象,其实是在jvm中,由类加载器根据类的全限定名来读取对应类的二进制字节流,并且转化为一个与目标类型对应的java.lang.Class对象实例。
二、方式
@Data
class Person {
private String userName;
private int age;
public void print(String parameter){
System.out.println(parameter);
}
public void noParameterPrint(){
System.out.println("没参数的方法");
}
public static void staticFunction(){
System.out.println("没参数的静态方法");
}
}
1、对象调用getClass()方式
Person person = new Person();
Class<? extends Person> clazz = person.getClass();
Arrays.asList(clazz.getDeclaredFields()).forEach(item -> {
System.out.println(item.getType() + "-------" + item.getName());
});
2、类名.class
Class<? extends Person> clazz2 = Person.class;
Arrays.asList(clazz2.getDeclaredFields()).forEach(item -> {
System.out.println(item.getType() + "-------" + item.getName());
});
3、Class.forName()
try {
Class<?> clazz3 = Class.forName("com.example.reflect.test.Person");
Arrays.asList(clazz2.getDeclaredFields()).forEach(item -> {
System.out.println(item.getType() + "-------" + item.getName());
});
try {
Method print = clazz3.getDeclaredMethod("print", String.class);
Method noParameterPrint = clazz3.getDeclaredMethod("noParameterPrint");
Method staticFunction = clazz3.getDeclaredMethod("staticFunction");
Object instance = clazz3.newInstance();
print.invoke(instance, "动态调用有参数的方法");
noParameterPrint.invoke(instance);
// 静态方法可以直接传实例或者null
staticFunction.invoke(null);
staticFunction.invoke(instance);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException e) {
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
三、常用api
getName():获得类的完整名字。
getFields():获得类的public类型的属性。
getDeclaredFields():获得类的所有属性。包括private 声明的和继承类
getMethods():获得类的public类型的方法(包括父类的)。
getDeclaredMethods():获得类的所有方法(不包括父类的)。
getMethod(String name, Class[] parameterTypes):获得类的特定方法,name参数指定方法的名字,parameterTypes 参数指定方法的参数类型。
getConstructors():获得类的public类型的构造方法。
getConstructor(Class[] parameterTypes):获得类的特定构造方法,parameterTypes 参数指定构造方法的参数类型。
newInstance():通过类的构造方法创建这个类的一个对象实例。