Loop over all fields in a Java class

Yes, with reflection.

Use the Class object to access Field objects with the getFields() method.

Field[] fields = ClassWithStuff.class.getFields();

Then loop over the fields. This works because all fields you have declared are public. If they aren't, then use getDeclaredFields(), which accesses all Fields that are directly declared on the class, public or not.


What are looking for is called reflection. Reflection lets you look at your own class, or another class to see what it is made of. Java has reflection built in, so you can use it right away. Then you can do stuff like -

for(Field f : ClasWithStuff.getFields()){
    System.out.println(f.getName());//or do other stuff with it
}

You can also use this to get methods, constructors, etc, to do similar and cooler stuff.


Use getDeclaredFields on [Class]

ClasWithStuff myStuff = new ClassWithStuff();
Field[] fields = myStuff.getClass().getDeclaredFields();
for(Field f : fields){
   Class t = f.getType();
   Object v = f.get(myStuff);
   if(t == boolean.class && Boolean.FALSE.equals(v)) 
     // found default value
   else if(t.isPrimitive() && ((Number) v).doubleValue() == 0)
     // found default value
   else if(!t.isPrimitive() && v == null)
     // found default value
}

(http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Class.html)

Tags:

Java

Class

Field