I have a class hierarchy like so: (=> means "is a subclass of")
anonymous instance class => abstract class => generic abstract class
or more succinctly:
C => B => A
When executing, "C" calls one of "A"'s methods. Within that method in "A", I want to use reflection to find protected fields of the object that are defined in class "B". (So these are fields that "C" and "B" can see, but not "A".)
How would I do this with Java reflection? And how can I future-proof it in case I add something between A & B or B & C?
We can get and set the value of a field in an Object using reflection. get() method return Object, so if field is primitive type, it returns the corresponsing Wrapper Class. If the field is static, we can pass Object as null in get() method.
The getDeclaredFields() method of java. lang. Class class is used to get the fields of this class, which are the fields that are private, public, protected or default and its members, but not the inherited ones. The method returns the fields of this class in the form of array of Field objects.
The list of all declared fields can be obtained using the java. lang. Class. getDeclaredFields() method as it returns an array of field objects.
It can then be discovered using the java. util. ServiceLoader class which, when given a Class object, will generate instances of all the declared subclasses of that class (or, if the Class represents an interface, all the classes implementing that interface).
You have to use getDeclaredFields()
repeatedly on each class in the inheritance hierarchy of your object's class (via getSuperclass()
).
However, what you are planning sounds like a nasty violation of the concept of inheritance. The best way of future-proofing would be to avoid this kind of thing entirely. What are you trying to do that you think requires such reflection shenanigans?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With