Accessing a parent class's protected method from outside a child class (with reflection or anything that would work)

StackOverflow https://stackoverflow.com//questions/10649940

Question

I've looked around for a solution with no luck, here's what I have and what I'm trying to achieve

Parent Class

public abstract class MyAbstractParentClass{
     private String privateParentField;

     protected String getPrivateParentField(){
          return privateParentField;
     }

     public void setField(String value){
          privateParentField = value;
     }
}

Child Class

public class MyChlidClass extends MyAbstractParentClass{
     @Override
     public void setField(String value){
          super.setField(value);
     }
}

I'm trying to call the MyChlidClass 's setField method and then call the MyAbstractParentClass 's protected String getPrivateParentField() afterwords;

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

But this code above returns only declared methods in MyChlidClass without the parent class's protected ones, how could I access the protected method? any ideas?

thank you very much in advance :)

EDIT Here's the final solution for those interested

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

PS : there are some exceptions you can either catch or add throws declaration for them;

thanks again for your help

Was it helpful?

Solution

You can get the super class methods by calling

MyChlidClass.class.getSuperclass().getDeclaredMethods();

OTHER TIPS

You cannot access protected methods directly from outside class. It can only be accessed from within the class or inherited classes. To access this from outside, you will have to create a public method in the child class that calls the protected method of the parent.

You can increase the visibility when you extend a class. You don't need to change the code of MyChlidClass, you can just extend it:

public class MyGrandChlidClass extends MyChlidClass{

     @Override
     public String getPrivateParentField(){
          return super.getPrivateParentField();
     }
}

@Test
public void f(){
    MyGrandChlidClass myGrandChlidClass = new MyGrandChlidClass();
    myGrandChlidClass.setField("hello");
    System.out.println(myGrandChlidClass.getPrivateParentField());
}

Use getDeclaredMethods() on the parent class to get information about the parent classes' protected methods.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top