Suppose I have the class
class car
{
int color = 1;
seats carSeats = new seats();
class seats
{
int numSeats = 4;
}
}
Using Java reflection, I can use the following:
car c = new car();
Field[] carFields = c.getClass().getDeclaredFields();
carFields would have { color, carSeats } as the fields. The instance, carSeats, has another field called numSeats.
Technically, I should be able to do another getFields() operation such that:
Field[] seatFields = carFields[1].getClass().getDeclaredFields();
But I am given garbage data (DECLARED, PUBLIC?) Why so? Does Java reflection not work for inner classes?
You could use Traverser class of java-util library which traverse every field of a class with the support of nested fields, which is what you want.
Here is a short snippet that can give some hints on Reflection
public class Car {
}
I find it good fun to use write code that uses reflection, but really hard to trouble shoot...
carFields[1].getClass()
is going to represent aField
object. You wantcarFields[1].getType().getDeclaredFields()
.Also, as BalusC commented, be careful. The fields aren't necessarily in the order you expect.