首頁 >Java >java教程 >java反射

java反射

大家讲道理
大家讲道理原創
2016-11-09 10:26:561481瀏覽

利用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();
    }
}


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn