从子类外部访问父类的受保护方法(使用反射或任何可行的方法)

sna*_*ahi 2 java testing reflection junit powermock

我一直在寻找一个没有运气的解决方案,这就是我拥有的和我想要实现的目标

家长班

public abstract class MyAbstractParentClass{
     private String privateParentField;

     protected String getPrivateParentField(){
          return privateParentField;
     }

     public void setField(String value){
          privateParentField = value;
     }
}
Run Code Online (Sandbox Code Playgroud)

儿童班

public class MyChlidClass extends MyAbstractParentClass{
     @Override
     public void setField(String value){
          super.setField(value);
     }
}
Run Code Online (Sandbox Code Playgroud)

我想调用MyChlidClasssetField方法,然后调用MyAbstractParentClassprotected String getPrivateParentField()后记;

@Test
public void f(){
    Method[] m = MyChlidClass.class.getDeclaredMethods();
    for (Method method : m) {
        System.out.println(method.getName());
    }
}
Run Code Online (Sandbox Code Playgroud)

但是上面的代码只返回声明的方法MyChlidClass而没有父类的protected方法,我怎样才能访问受保护的方法?有任何想法吗?

非常感谢你提前:)

编辑 这是有兴趣的人的最终解决方案

MyChildClass child = new MyChildClass();
chlid.setField("FOO_BAR");

Method getPrivateParentField = child.getClass().getSuperclass().getDeclaredMethod("getPrivateParentField");
getPrivateParentField.setAccessible(true);

String result = (String) getPrivateParentField.invoke(child);
System.out.println((String)result); //prints out FOO_BAR
Run Code Online (Sandbox Code Playgroud)

PS:有一些例外,您可以捕获或添加抛出声明;

再次感谢你的帮助

mpr*_*hat 6

您可以通过调用获取超类方法

MyChlidClass.class.getSuperclass().getDeclaredMethods();
Run Code Online (Sandbox Code Playgroud)