1.回顾反射
反射就是在程序运行时动态获取到自身的信息,包括类信息、构造器、属性、方法等。
public class Car {
......
}//1 获取class对象
Car.class
new Car().getClass()
Class a = Class.forname("类路径")//2.获取到class对象后实例化
Car b = (Car)a.getConstructor().newInstance()//3.获取构造器
a.getDeclaredConstructors()
a.getConstructor(String.class,int.class)//4.获取属性
Field[] c = a.getFields()
Field d = c[0]
d.getName()
d.setAccessible(true)
d.set(a,"value")//5.获取方法
Method[] e = a.getMethods()
Method f = e[0]
f.getName()
f.setAccessible(true)
String g = (String)f.invoke(a)