Java访问类中private属性和方法


一般在其他类中是不能这个得到类中private属性和访问private方法的,但天无绝人之路,java强大的反射机制可以完成这个任务。

建一个测试类A:

  1. package com.shao.test;  
  2.   
  3. public class A {  
  4.     private String testStr="just for test";  
  5.     private void get(int index,String value){  
  6.         System.out.println(index+":"+value+" and testStr:"+testStr);  
  7.     }  
  8. }  

现在我们来访问A中的testStr属性和get方法:

  1. package com.shao.test;  
  2.   
  3. import java.lang.reflect.Field;  
  4. import java.lang.reflect.InvocationTargetException;  
  5. import java.lang.reflect.Method;  
  6.   
  7. public class B {  
  8.       public static void main(String[]args) throws ClassNotFoundException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException, NoSuchMethodException, InvocationTargetException{  
  9.             Field field=Class.forName("com.shao.test.A").getDeclaredField("testStr");  
  10.             field.setAccessible(true);  
  11.             A a=new A();  
  12.             System.out.println(field.getType().toString());   //print:class java.lang.String   
  13.             System.out.println(field.getName());              //print:testStr   
  14.             System.out.println(field.getModifiers());         //print:2   
  15.             Object s=field.get(a);  
  16.             System.out.println(s);                            //print:just for test   
  17.             String x="Hello";  
  18.             field.set(a, x);  
  19.             System.out.println(field.get(a));                 //print:Hello   
  20.             Method method=Class.forName("com.shao.test.A").getDeclaredMethod("get"new Class[]{int.class,String.class});  
  21.             method.setAccessible(true);  
  22.             method.invoke(a, 3,"apples");   //print:3:apples and testStr:Hello   
  23.         }  
  24. }  

属性使用Filed类获取,方法使用Method类去调用。

相关内容