Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over object attributes in java [duplicate]

Tags:

java

database

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!

like image 234
tgm Avatar asked Sep 19 '11 08:09

tgm


2 Answers

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/

like image 142
Jayendra Avatar answered Sep 20 '22 10:09

Jayendra


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.

like image 28
Thomas Avatar answered Sep 17 '22 10:09

Thomas