Possible Duplicate:
How to loop over a Class attributes in Java?
class Foo{
int id;
String name;
int bar;
int bar2;
//..
}
Foo foo = new Foo();
Is there a way to iterate over this object attributes in java? I want to create an INSERT query and i have to convert all int attributes in Strings. It is a little problematic when there are more attributes of different types.
Thanks!
Class cls = Class.forName("Foo");
Field[] fields = cls.getDeclaredFields();
Should return all the declared fields for the class using reflection. More info @ http://java.sun.com/developer/technicalArticles/ALT/Reflection/
If the order of the properties is not relevant use Apache Commons BeanUtils:
Foo foo = new Foo();
Map<String, Object> fields = (Map<String, Object>) BeanUtils.describe(foo);
Note that BeanUtils
doesn't use generics, hence the cast.
Additional note: your objects have to adhere to the JavaBeans specification in order to use this approach.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With