【入門】反射-對理解動態代理有幫助

前言

反射之所以被稱爲框架的靈魂,主要是因爲它賦予了我們在運行時分析類以及執行類中方法的能力。
通過反射你可以獲取任意一個類的所有屬性方法,你還可以調用這些方法和屬性。

來自:JavaGuide

示例

public class Main {

    public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {

        User user = new User("wang", 12);
        Class<? extends User> aClass = user.getClass();

        for (Method declaredMethod : aClass.getDeclaredMethods()) {
            if (declaredMethod.getName().equals("setName")) {
                declaredMethod.invoke(user, "liu");
            }

            if (declaredMethod.getName().equals("test")) {
                declaredMethod.setAccessible(true);
                System.out.println(declaredMethod.invoke(user));
            }
            System.out.println("方法名:" + declaredMethod.getName());
        }

        for (Field declaredField : aClass.getDeclaredFields()) {
            System.out.println("字段名:" + declaredField.getName());
        }
        
        System.out.println(user.toString());
    }

}

方法名:toString
方法名:getName
test
方法名:test
方法名:setName
方法名:setAge
方法名:getAge
字段名:name
字段名:age
User{name='liu', age=12}

總結

invoke 方法在動態代理中也有使用。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章