Quick edit: As was pointed out below I should be doing a BFS but I need a point to stop retrieving new fields, which I haven't had time to think about yet. Thanks for all the help!
I'm trying to use Java reflection to recursively get the fields of classes, essentially creating a tree to display
Class
field1 class
field1.1 class
field1.2 class
field2 class
field 2.1 class
field 2.2 class
This is for a recursive decent parser, so I figured a recursive display function would be cool to make. Unfortunately it's crushing me.
Example class Foo, with fields of Class1 and Class2, each of which could have more fields of different classes:
class Assignment extends Statement {
Variable target;
Expression source;
Assignment (Variable t, Expression e) {
target = t;
source = e;
}
My recursive method:
private void recurse(Object object){
System.out.println(object.getClass());
for (Field field : object.getClass().getDeclaredFields()){
System.out.println(field.getType());
System.out.println(field.getName());
if(!field.getType().isPrimitive() || field.getType() instanceof Class || field.getName() != "clazz"){
//recurse(field);
}
}
The println has been for testing and an example output for Foo would be (without recursion, it seems to work) giving
class Assignment
class Variable
target
class Expression
source
But I can't figure out how to take the Variable class and then get its fields and so on. The field that contains this information gives me a class Field.
Also, I realize I need a point to stop the recursion but stopping at primative fields doesn't seem to work. Any suggestions would be useful and really help me understand the nitty-gritty of what I seem to be flailing around in.
Side note: for the means of this class that this is for I know I can just put a display method in for each class and call those, but I the process of reflection seemed more interesting and possibly reusable.
TLDR: How do I get the class of the actual field contained in a Field?
Sorry if I'm missing anything, first question I've asked.
Thanks for your time!
-Alex