Java的反射可以取得一个类的所有信息,包括里面的属性、方法以及构造函数等,甚至可以取得其父类或父类接口里面的内容。以下是关于反射的知识框架

关于反射

反射的使用方法:

  1. System.out.println("-----------------属性-----------------------");  
  2.         // 1.得到你的类的对象  
  3.         Class c = Class.forName("com.zking.entity.Person");  
  4.         Field f = c.getDeclaredField("pname");  
  5.         // 设置私有的属性能够被访问  
  6.         f.setAccessible(true);  
  7.         System.out.println(f);  
  8.         // 得到一个person对象 newInstance 产生一个新的实列 实列化对象  
  9.         Object person = c.newInstance();  
  10.         // 赋值  
  11.         f.set(person, "东东");  
  12.         // 取值  
  13.         f.get(person);  
  14.         System.out.println(f.get(person));  
[html] view plain 
[html] view plain copy
  1. //获取所有属性  
  2.          Class c = Class.forName("com.zking.entity.Person");  
  3.         Field[] fields = c.getDeclaredFields();  
  4.         Object person = null;  
  5.         for (Field f : fields) {  
  6.         f.setAccessible(true);  
  7.          person = c.newInstance();  
  8.          if ("pid".contains(f.getName())) {  
  9.          f.set(person, "M01");  
  10.          } else if ("pname".contains(f.getName())) {  
  11.         f.set(person, "张三");  
  12.         } else if ("sex".contains(f.getName())) {  
  13.         f.set(person, 18);  
  14.         }  
  15.        System.out.println(f.get(person));  
  16.         }  

相关文章: