I have a class which has several fields which are a subclass of another class. I want to quickly find all instances of that subclass within the top level class.
For example
public class TopClass {
private ClassIWant1 myVar1;
private ClassIWant2 myVar2;
private OtherJunk myVar3;
private Nested myVar4;
}
public class Nested {
private ClassIWant3 myVar11;
}
public class SuperClass {
}
public ClassIWant1 extends SuperClass {}
public ClassIWant2 extends SuperClass {}
public ClassIWant3 extends ClassIWant1 {}
If I were to run that example through with an instance of TopClass I would expect to get a List containing the values for myVar1, myVar2, and myVar11.
I have a general idea of how to use reflection to do this manually, but I’m hoping that I don’t have to reinvent the wheel. Is there a library that can do this?
I am familiar with ReflectUtils, but I am not sure if that can do this or not.
If I understand your request correctly, you’re looking for something like this:
This works by using the static types of the fields as declared. That is, if you declare a field as
Objectbut it holds an instance ofSuperClassor one of its descendants, it won’t be found. It will also returnnulls if the fields have them set as the value. I have no idea what this will do about primitive types.Disclaimer: Code was tested briefly on an optimistic example, I hold no responsibility if it causes your computer to catch fire.