概述
一. 访问自身的私有方法,成员变量
1 ) 比如我们有PrivateClassA.java
public class PrivateClassA {
private Map<String, String> map = new HashMap<String, String>();
public PrivateClassA(){
map.put("a", "a");
map.put("b", "b");
}
public void getPublic(){
System.out.println("hi, I'm public method");
}
@SuppressWarnings("unused")
private void getPrivate(){
System.out.println("hi, I'm private method");
}
}
2 ) 访问测试用例如下
public class PrivateClassATest {
@Test
public void testAccessPublic() throws Exception{
Method med = PrivateClassA.class.getMethod("getPublic", new Class[]{});
med.invoke(PrivateClassA.class.newInstance(), new Object[]{});
Method med2 = PrivateClassA.class.getDeclaredMethod("getPublic", new Class[]{});
med2.invoke(PrivateClassA.class.newInstance(), new Object[]{});
}
@Test
public void testAccessPrivate() throws Exception{
Method med = PrivateClassA.class.getDeclaredMethod("getPrivate", new Class[]{});
med.setAccessible(true);
med.invoke(PrivateClassA.class.newInstance(), new Object[]{});
}
// Access the private attribute
@SuppressWarnings("unchecked")
@Test
public void testAccessPrivateAttribute() throws Exception{
// 如果访问的是私有变量,要用 getDeclaredField
Field f = PrivateClassA.class.getDeclaredField("map");
f.setAccessible( true );
Map<String, String> map = (Map<String, String>) f.get( new PrivateClassA() );
Assert.assertEquals( map.size(), 2 );
Iterator<String> keyIter = map.keySet().iterator();
Assert.assertEquals( keyIter.next(), "a" );
Assert.assertEquals( keyIter.next(), "b" );
}
}
二. 访问超类的私有方法,成员变量
1 ) 比如我们有如下的子类和父类
// Super Class
public class PrivateFather {
private void saidToChildren(){
System.out.println("hi, child, I'm your private father");
}
}
// Children
public class PrivateChildren extends PrivateFather{
}
2 ) 创建一个访问私有方法的工具类
public class ReflectionUtils {
public static Method findMethod(Class srcClass, String name, Class[] parameters) throws NoSuchMethodException{
Method method = null;
try {
method = srcClass.getDeclaredMethod(name, parameters);
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
if( srcClass.getSuperclass() == null ) throw e;
else{
return findMethod(srcClass.getSuperclass(), name, parameters);
}
}
return method;
}
}
3 ) Junit Test cases
public class FatherPrivateMethodTest{
@Test
public void testGetPrivateFromFather() throws IllegalArgumentException,
IllegalAccessException, InvocationTargetException, InstantiationException{
Method superPrivateMed = null;
try {
superPrivateMed = ReflectionUtils.findMethod(PrivateChildren.class, "saidToChildren", null);
superPrivateMed.setAccessible(true);
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
superPrivateMed.invoke(PrivateChildren.class.newInstance(), null);
superPrivateMed.invoke(new PrivateChildren(), null);
}
}
最后
以上就是淡然皮皮虾为你收集整理的Java 基础 - Reflection: 访问私有的方法,成员变量的全部内容,希望文章能够帮你解决Java 基础 - Reflection: 访问私有的方法,成员变量所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复