分享

java反射设置私有属性和获取属性

 干掉熊猫,我就是国宝 2010-12-24
Java代码
  1. package com;  
  2.   
  3. import java.lang.reflect.Field;  
  4. import java.lang.reflect.InvocationTargetException;  
  5. import java.lang.reflect.Method;  
  6.   
  7.   
  8.   
  9. public class TestBean {  
  10.     private int age;  
  11.   
  12.       
  13.     public static void main(String []args) throws InstantiationException, IllegalAccessException, SecurityException, NoSuchFieldException{  
  14.         try {  
  15.             Class<?> class1=Class.forName("com.TestBean");  
  16.             Object tObject=class1.newInstance();  
  17.             Field field=class1.getDeclaredField("age");  
  18.             field.setAccessible(true);  //设置私有属性范围  
  19.             field.set(tObject, 10);    
  20.             System.out.print(field.get(tObject));  
  21.           
  22.             try {  
  23.                 Method method=class1.getMethod("setAge"int.class);  
  24.                 method.invoke(tObject, 11);  
  25.                   
  26.                 Method getMethod=class1.getMethod("getAge");  
  27.                 System.out.println(getMethod.invoke(tObject));  
  28.                   
  29.             } catch (NoSuchMethodException e) {  
  30.                 // TODO Auto-generated catch block  
  31.                 e.printStackTrace();  
  32.             } catch (IllegalArgumentException e) {  
  33.                 // TODO Auto-generated catch block  
  34.                 e.printStackTrace();  
  35.             } catch (InvocationTargetException e) {  
  36.                 // TODO Auto-generated catch block  
  37.                 e.printStackTrace();  
  38.             }  
  39.               
  40.               
  41.         } catch (ClassNotFoundException e) {  
  42.             // TODO Auto-generated catch block  
  43.             e.printStackTrace();  
  44.         }  
  45.           
  46.           
  47.     }  
  48.   
  49.   
  50.     public int getAge() {  
  51.         return age;  
  52.     }  
  53.   
  54.   
  55.     public void setAge(int age) {  
  56.         this.age = age;  
  57.     }  

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多