直接上码使用方式:
public class Car {
private String brand;
private String color;
private int maxSpeed;
public Car() {}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getMaxSpeed() {
return maxSpeed;
}
public void setMaxSpeed(int maxSpeed) {
this.maxSpeed = maxSpeed;
}
public Car(String brand,String color,int maxSpeed){
this.brand = brand;
this.color = color;
this.maxSpeed = maxSpeed;
}
public void introduce(){
System.out.println("brand: " + brand + " color: " + color + " maxSpeed: " + maxSpeed);
}
}
public class ReflectTest {
public static Car initByDefaultConst() throws Throwable {
//通过类装载器获取Car类对象
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
Class clazz = classLoader.loadClass("Car");
//找到默认构造函数并生成对象
Constructor constructor = clazz.getDeclaredConstructor((Class[]) null);
Car car = (Car) constructor.newInstance();
//通过反射方法设置属性
Method setBrand = clazz.getMethod("setBrand",String.class);
setBrand.invoke(car,"Bens");
Method setColor = clazz.getMethod("setColor",String.class);
setColor.invoke(car,"Red");
Method setMaxSpeed = clazz.getMethod("setMaxSpeed",int.class);
setMaxSpeed.invoke(car,45);
return car;
}
public static void main(String[] args) throws Throwable{
initByDefaultConst().introduce();
}
}
类装载器ClassLoader把类装载进JVM需要经过以下步骤:
- 装载:查找和导入类文件。
- 链接:执行校验、准备和解析。
- 校验:检测类数据是否正确。
- 准备:给类静态变量分配空间。
- 解析:将符号引用改为直接引用。
- 初始化:对类的静态变量和代码执行初始化工作。
JVM运行时会生成三个ClassLoader:根装载器,ExClassLoader(拓展类装载器)
、AppClassLoader(系统类装载器),其中根装载器是C++文件,AppClassLoader和ExClassLoader都是ClassLoader的子类,AppClassLoader是ExClassLoadee的子类。根装载器负责装载Jre核心类库,ExClassLoader装载jre拓展库,AppClassLoader负责应用程序类。装载顺序是只有父ClassLoader找不到文件才到子ClassLoader装载。