The class ExtendedDismaxQParser has a static member class Clause:
public class ExtendedDismaxQParser {
protected static Class Clause {
protected String foo, bar;
}
public Clause getAClause {
Clause c;
// misc code that isn't important
return c;
}
}
I then extended this class in a different 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 can't access the foo member variable, despite the fact that the class Clause is protected, and the member variable foo is also protected.
I just want to be able to check something about the member variable foo of the protected static class Clause. How can I do this (preferably without reflection)?
I would greatly prefer to not have to modify the parent class because it is a part of a library.
aioobe's comment is correct.
Sharing a superclass with the outer class isn't enough to get access to protected members of the static inner class.
The caller's class doesn't extend Clause, and is in a different package. For protected
to be relevant you'd have to access foo from within a subclass of Clause, or access it from a class in the same package as ExtendedDismaxQParser.
As already been said in the comments and very well explained in the answer by @Nathan Hughes, you can not access the protected
field in Clause
as it is not the class being extended.
The only way to access this field is unfortunately 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();
}
}
}
Protected access modifiers allow variables and methods to be accessed within the package only. You have create your class inside the package of your Clause class.
Reflection will not do you any good here.