Access to the protected member of the static class in the subclass of the parent

The ExtendedDismaxQParser class has a static class member. Klaus:

public class ExtendedDismaxQParser { protected static Class Clause { protected String foo, bar; } public Clause getAClause { Clause c; // misc code that isn't important return c; } } 

Then I extended this class in another package:

 public class SpecialDismaxQParser extends ExtendedDismaxQParser { public void whatever() { Clause c = super.getAClause(); boolean baz = c.foo.equals("foobar"); // <-- This doesn't compile } } 

It looks like you cannot access the foo member variable, although the Clause class is protected, as well as the foo member variable.

I just want to check something about the foo member variable of Clause's protected static class. How can I do this (preferably without reflection)?

I would prefer not to change the parent class, because it is part of the library.

+2
source share
3 answers

Comment aioobe correct.

Sharing a superclass with an outer class is not enough to access the protected members of a static inner class.

The caller class does not extend the offer and is in a different package. In order for protected be relevant, you will need to access foo from the Clause subclass or access it from the class in the same package as ExtendedDismaxQParser.

+1
source

As already mentioned in the comments and very well explained in @Nathan Hughes answer, you cannot access the protected field in Clause , since this is not an extension of the class.

The only way to access this field, unfortunately, is through reflection

 public class SpecialDismaxQParser extends ExtendedDismaxQParser { public void whatever() { try { Field fooField = Clause.class.getDeclaredField("foo"); fooField.setAccessible(true); Clause c = super.getAClause(); boolean baz = fooField.get(c).equals("foobar"); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } } 
0
source

Protected access modifiers allow access to variables and methods only in the package. You created your class inside the package of your Clause class.

Reflection here will not help you.

-2
source

Source: https://habr.com/ru/post/1245674/


All Articles