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);
}

猜你喜欢

转载自blog.csdn.net/qq_40298054/article/details/89197494