Java反射 field
生活随笔
收集整理的這篇文章主要介紹了
Java反射 field
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Java反射 field
獲取字節碼文件對象
Class c = Class.forName(“fieldtest.Student”);
通過無參構造方法創建對象obj
Constructor con = c.getConstructor();
Object obj = con.newInstance();
通過成員變量名,獲取單個的成員變量
Field nameField = c.getField("name");//getField(String name)//Returns a Field object that reflects the specified public member field of the class or interface represented by this Class object. //The name parameter is a String specifying the simple name of the desired field將指定對象變量上此 Field 對象表示的字段設置為指定的新值
nameField.set(obj, "y"); // 給obj對象的addressField字段設置值為"y"// public void set(Object obj,Object value)設置與Field對象對應的obj對象中的域的值為value如果想要獲取指定私有成員變量
Field ageField = c.getDeclaredField(“age”);
取消對私有變量age的訪問檢查
ageField.setAccessible(true);
將指定對象變量上此 Field 對象表示的字段設置為指定的新值
ageField.set(obj, 18);
總結
以上是生活随笔為你收集整理的Java反射 field的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 手机屏幕什么计算机,windows 7系
- 下一篇: java美元兑换,(Java实现) 美元