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
You can get the super class methods by calling