您的位置:首页 > 其它

利用反射访问私有属性、调用私有方法

2014-02-28 09:45 676 查看
访问私有属性的代码:

package com.tyxh.create;

public class Customer {
private int a = 1;

public int getA() {
return a;
}

}

package com.tyxh.create;

import java.lang.reflect.Field;

public class Private {

public static void main(String[] args) throws Exception {
//实例化
Customer customer = (Customer) Class.forName("com.tyxh.create.Customer").newInstance();

System. out.println( "修改之前 : " + customer.getA());

Class<? extends Customer> c = customer.getClass();

Field field = c.getDeclaredField( "a");

field.setAccessible( true);

field.set(customer, 2);

System. out.println( "修改之后: " + customer.getA());

}
}

调用私有方法的代码:
package com.tyxh.create;

public class Customer {

private String b1(String n) {
return "你好啊," + n + " ,你都访问我私有方法啦。。。NB 啊" ;
}

private void b2() {
System. out.println( "我擦,都访问我私有方法了啊。。。碉堡了" );
}
}
package com.tyxh.create;

import java.lang.reflect.Method;

public class Private {

public static void main(String[] args) throws Exception {
Customer customer = (Customer) Class.forName("com.tyxh.create.Customer").newInstance();
Class<? extends Customer> c = customer.getClass();

Method m1 = c.getDeclaredMethod( "b1", new Class[]{String.class});
m1.setAccessible( true);
String str = (String) m1.invoke(customer, new Object[]{"tyxh"});
System. out. println(str);

Method m2 = c.getDeclaredMethod("b2", null) ;
m2.setAccessible( true);
m2.invoke(customer, null);

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息