Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java reflection: Find fields of a subclass

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?

like image 922
roufamatic Avatar asked Jan 31 '10 15:01

roufamatic


People also ask

How do you find the object of a class using reflection?

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.

How do you find the declared field of a class?

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.

How do you find all fields?

The list of all declared fields can be obtained using the java. lang. Class. getDeclaredFields() method as it returns an array of field objects.

How do you find all subclasses of a given class in Java?

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).


1 Answers

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?

like image 96
Michael Borgwardt Avatar answered Nov 15 '22 23:11

Michael Borgwardt