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

java反射

大家讲道理
大家讲道理原创
2016-11-09 10:26:561484浏览

利用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