Java反射技术的简单使用


实例:

一个普通了类:给定了string对象的值,下面利用反射技术要将name的值换成ddd

  1. public class haha {   
  2. public String name = "bbb";   
  3. public String sex = "dddd";   
  4.     
  5.     public String getName() {   
  6.     return name;   
  7.     }   
  8.     
  9. }  

测试类:

  1. import java.lang.reflect.Constructor;   
  2. import java.lang.reflect.Field;   
  3. import java.lang.reflect.InvocationTargetException;   
  4. public class tt {   
  5. public static void main(String[] args) throws IllegalArgumentException,   
  6. IllegalAccessException, ClassNotFoundException, SecurityException,   
  7. NoSuchMethodException, InstantiationException,   
  8. InvocationTargetException {   
  9. // 获得一个String类型String(StringBuffer stringbuffer)构造方法对象   
  10. Constructor constructor = String.class  
  11. .getConstructor(StringBuffer.class);   
  12. // 根据constructor对象构建一个新的字符串对象   
  13. String strs = (String) constructor   
  14. .newInstance(new StringBuffer("jjjjj"));   
  15. System.out.println("利用反射技术new了一个字符串:" + strs);   
  16.     
  17. try {   
  18. haha h = new haha();   
  19. System.out.println("反射操作前的值是:" + h.name);   
  20. // 得到haha类字节码   
  21. Class hh = Class.forName("test.haha");   
  22. // 得到name属性的对象   
  23. Field filed = hh.getField("name");   
  24. // 根据对象获得具体对象(h)中的name属性值   
  25. String value = (String) filed.get(h);   
  26. String newvalue = value.replace("b""d");   
  27. // 为name属性设置新的值   
  28. filed.set(h, newvalue);   
  29.     
  30. System.out.println("反射操作后的值是" + h.name);   
  31. catch (SecurityException e) {   
  32.     
  33. e.printStackTrace();   
  34. catch (NoSuchFieldException e) {   
  35.     
  36. e.printStackTrace();   
  37. }   
  38.     
  39. }   
  40.     
  41. }  

相关内容