今天遇到一个问题,别人问我如何在外部访问类的私有属性?
我很奇怪,我直接new这个对象不就可以获取了吗? new Person().getName();这样不就可以获取这个类的私有属性值了吗?
不过对方说不是这种方式,后来我查了下,可以通过反射的机制来获取该属性和方法:
类对象
public class Examp {
public int pub = 3;
private int a = 4;
private String s = "123";
public void demo01(){
System.out.println("======demo01===========");
}
private void demo02(){
System.out.println("======demo02===========");
}
private void demo03(String s){
a++;
System.out.println("======demo03===s:"+s+"========a:"+a);
}
}
测试类:
public static void main(String args[]){
Examp e=new Examp(); //初始化Exam实例
try {
Field pub = e.getClass().getDeclaredField("pub");
System.out.println("pub: "+pub.get(e));
Field a = e.getClass().getDeclaredField("a");
Field s = e.getClass().getDeclaredField("s");
a.setAccessible(true);
s.setAccessible(true);
System.out.println("s: "+s.get(e));
s.set(e,"sss");
System.out.println("新的s: "+s.get(e));
System.out.println("a: "+a.get(e));
a.set(e,8);
System.out.println("新的a: "+a.get(e));
} catch (NoSuchFieldException e1) {
e1.printStackTrace();
}catch (IllegalArgumentException e1) {
e1.printStackTrace();
} catch (IllegalAccessException e1) {
e1.printStackTrace();
}
try {
Method method1 = e.getClass().getDeclaredMethod("demo01");
method1.invoke(e);
Method method2 = e.getClass().getDeclaredMethod("demo02");
method2.setAccessible(true);
method2.invoke(e);
Method method3 = e.getClass().getDeclaredMethod("demo03",String.class);
method3.setAccessible(true);
method3.invoke(e,"ffff");
} catch (NoSuchMethodException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SecurityException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}catch (IllegalAccessException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalArgumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InvocationTargetException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
结果:
pub: 3
s: 123
新的s: sss
a: 4
新的a: 8
======demo01===========
======demo02===========
======demo03===s:ffff========a:9
如上可以获取类的属性,值和方法,不过这种方式就是说你必须知道这个类的属性或方法的名字