通過Java反射動態獲取資訊

lvzhou_MadSky發表於2013-06-07

public static  Car getCarInfo() throws Throwable{
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        Class clazz = loader.loadClass("test.Car");
       
        Constructor constructor = clazz.getDeclaredConstructor((Class[])null);
        Car car = (Car) constructor.newInstance();
       
        Method setCarType = clazz.getMethod("setCarType",String.class);
        setCarType.invoke(car, "奧迪Q7");
        //動態設定屬性值
        Method setCarColor = clazz.getMethod("setCarColor", String.class);
        setCarColor.invoke(car, "爵士黑");
        //動態獲取屬性值
        Method getCarColor = clazz.getMethod("getCarColor");
        String color = (String) getCarColor.invoke(car);
        System.out.println("【顏色】="+color);
       
        Method setCarPrice = clazz.getMethod("setCarPrice",int.class);
        setCarPrice.invoke(car, 1060000);
       
        return car;
    }

相關文章