通過java反射機制調用類中方法


import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ClassReflectTestDemo {
    public static void main(String[] args) throws Exception {

        String attribute="name";
        String value="MLDN";
        Class<?> cls= Class.forName("FanShejizhi.Person");//獲取類
        Object obj=cls.newInstance();//實例化類對象
        //取得setName這個方法的實例化對象  setName是一個方法的屬性名稱,
        // 這裏使用給定的屬性信息拼湊得到,同時改方法需要一個String型的參數
        Field field=cls.getDeclaredField(attribute);
        Method setMathod=cls.getMethod("set"+inincap(attribute),field.getType());
        //通過Method類對象調用指定的方法,調用方法必須有實例化對象  ,同時傳入所需參數
        setMathod.invoke(obj,value);
        Method getMethod=cls.getMethod("get"+inincap(attribute));
        Object ret =getMethod.invoke(obj);//等價於Person.getName()
        System.out.println(ret);
    }
    public static  String inincap(String string){
        return string.substring(0,1).toUpperCase()+string.substring(1);
    }
}

class Person {
    private String name;
    private int age;

    public Person() {
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}
發佈了43 篇原創文章 · 獲贊 42 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章