欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  Java

java反射

程序员文章站 2022-04-16 15:11:13
...
利用java反射方法设置属性
package com.baobaotao.reflect;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
 
/**
 * Created by xu on 2016/7/4.
 */
public class ReflectTest {
    public static Car initByDefaultConst() throws Throwable {
 
        //1.通过类装载器获取Car类对象
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        Class clazz = loader.loadClass("com.baobaotao.reflect.Car");
 
        //2.获取类的默认构造器对象并通过它实例化Car
        Constructor cons = clazz.getConstructor((Class[])null);
        Car car = (Car) cons.newInstance();
 
        //3.通过反射方法设置属性
        Method setBrand = clazz.getMethod("setBrand",String.class);
        setBrand.invoke(car,"红旗CA72");
        Method setColor = clazz.getMethod("setColor",String.class);
        setColor.invoke(car,"黑色");
        Method setMaxSpeed = clazz.getMethod("setMaxSpeed",int.class);
        setMaxSpeed.invoke(car,200);
 
        return car;
    }
 
    public static void main(String[] args) throws Throwable {
        Car car = initByDefaultConst();
        car.introduce();
    }
}