Java 反射机制

2017-03-11  本文已影响20人  mnikn

直接上码使用方式:

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装载。

上一篇下一篇

猜你喜欢

热点阅读