Home >Java >javaTutorial >java reflection

java reflection

大家讲道理
大家讲道理Original
2016-11-09 10:26:561479browse

Use java reflection method to set properties

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


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Improve code reusabilityNext article:Improve code reusability