配置依賴反射設置注入

package model;
public class Person {
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}
//下面通過反射對name進行set值
package model;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Test {
    public static void main(String[] args) throws SecurityException, NoSuchMethodException {
        try {
            Class personClazz=Class.forName("model.Person");
            try {
                Object bean=personClazz.newInstance();
                Method method1=  personClazz.getMethod("setName","xie".getClass());
                //調用bean實例的setName方法
                try {
                    method1.invoke(bean,"xie");
                    Person p=(Person)bean;
                    //測試是否已經將值set進去
                    System.out.println(p.getName());
                } catch (IllegalArgumentException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } catch (InstantiationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}
發佈了91 篇原創文章 · 獲贊 7 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章