Note that there are some explanatory texts on larger screens.

plurals
  1. POAccessing a parent class's protected method from outside a child class (with reflection or anything that would work)
    primarykey
    data
    text
    <p>I've looked around for a solution with no luck, here's what I have and what I'm trying to achieve</p> <p><strong>Parent Class</strong></p> <pre><code>public abstract class MyAbstractParentClass{ private String privateParentField; protected String getPrivateParentField(){ return privateParentField; } public void setField(String value){ privateParentField = value; } } </code></pre> <p><strong>Child Class</strong></p> <pre><code>public class MyChlidClass extends MyAbstractParentClass{ @Override public void setField(String value){ super.setField(value); } } </code></pre> <p>I'm trying to call the <code>MyChlidClass</code> 's <code>setField</code> method and then call the <code>MyAbstractParentClass</code> 's <code>protected String getPrivateParentField()</code> afterwords; </p> <pre><code>@Test public void f(){ Method[] m = MyChlidClass.class.getDeclaredMethods(); for (Method method : m) { System.out.println(method.getName()); } } </code></pre> <p>But this code above returns only declared methods in <code>MyChlidClass</code> without the parent class's <code>protected</code> ones, how could I access the protected method? any ideas? </p> <p>thank you very much in advance :)</p> <p><strong>EDIT</strong> Here's the final solution for those interested</p> <pre><code>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 </code></pre> <p>PS : there are some exceptions you can either catch or add throws declaration for them;</p> <p>thanks again for your help</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload