JAVA反射机制的本质是调用类的Class对象,通过操纵目标类Class对象来实现操纵目标对象
Class类对象是类装载器(ClassLoader)装载类之后,调用defineClass()生成的类的描述对象。
简单举例
package com.smart;
/**
* @Author windy
* @Desp
* @Date 2019-07-29 20:43
*/
public class Car {
private String brand;
private String color;
private int maxSpeed;
public Car(){}
public Car(String brand, String color, int maxSpeed){
this.brand = brand;
this.color = color;
this.maxSpeed = maxSpeed;
}
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;
}
@Override
public String toString() {
return "Car{" +
"brand='" + brand + '\'' +
", color='" + color + '\'' +
", maxSpeed=" + maxSpeed +
'}';
}
}
测试类
package com.smart;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
/**
* @Author windy
* @Desp
* @Date 2019-07-29 20:45
*/
public class ReflectTest {
public static Car initDefaultCar() throws Throwable {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
Class clazz = loader.loadClass("com.smart.Car");
Constructor cons = clazz.getDeclaredConstructor();
Car car = (Car) cons.newInstance();
Method setBrand = clazz.getMethod("setBrand", String.class);
setBrand.invoke(car, "大众");
Method setColor = clazz.getMethod("setColor", String.class);
setColor.invoke(car, "红色");
Method setMaxSpeed = clazz.getMethod("setMaxSpeed", int.class);
setMaxSpeed.invoke(car, 180);
return car;
}
public static void main(String[] args) throws Throwable {
System.out.println(initDefaultCar());
}
}
获取当前线程的ContextClassLoader, 使用loadClass() 方法去加载指定类,生成Class对象,通过Class对象的描述信息,去获取 getDeclaredConstructor() 构造器,有了构造器 就可以初始化类了,这是间接的操纵这个类,通过 getMethod() 方法获取指定的方法,使用invoke() 方法调用该方法。当然了 也可以获取属性。