JAVA反射練習

一、題目一

需求:ArrayList<Integer>的一個對象,在這個集合中添加一個字符串數據,如何實現呢?

提示:泛型只在編譯期有效,在運行期會被擦除掉

public static void main(String[] args) throws Exception {
   ArrayList<Integer> list = new ArrayList<>();
   list.add(111);
   list.add(222);
   
   Class clazz = Class.forName("java.util.ArrayList");             //獲取字節碼對象
   Method m = clazz.getMethod("add", Object.class);            //獲取add方法
   m.invoke(list, "abc");
   
   System.out.println(list);
}

二、題目二:

需求:已知一個類,定義如下: 

public class DemoClass {
      public void run() {
         System.out.println("welcome to heima!");
      }
}

(1) 寫一個Properties格式的配置文件,配置類的完整名稱。
(2) 寫一個程序,讀取這個Properties配置文件,獲得類的完整名稱並加載這個類,用反射的方式運行run方法。

public static void main(String[] args) throws Exception {
   BufferedReader br = new BufferedReader(new FileReader("xxx.properties"));//輸入流關聯xxx.properties
   Class clazz = Class.forName(br.readLine());                          //讀取配置文件中類名,獲取字節碼對象
   
   DemoClass dc = (DemoClass) clazz.newInstance();                         //通過字節碼對象創建對象
   dc.run();
}

三、題目三

需求:可將obj對象中名爲propertyName的屬性的值設置爲value的通用方法

public class Tool {
   public void setProperty(Object obj, String propertyName, Object value) throws Exception {
      Class clazz = obj.getClass();              //獲取字節碼對象
      Field f = clazz.getDeclaredField(propertyName);    //暴力反射獲取字段
      f.setAccessible(true);                   //去除權限
      f.set(obj, value);
   }
}
public static void main(String[] args) throws Exception {
   Student s = new Student("張三", 23);
   System.out.println(s);
   
   Tool t = new Tool();
   t.setProperty(s, "name", "李四");
   System.out.println(s);
}

 

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