开发者

Iterate over object attributes in java [duplicate]

This question already has answers here: 开发者_运维技巧 Closed 11 years ago.

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.


You can use Java Reflection to do so.


You can get all the fields of the Foo class by calling getDeclaredFields() method on the Foo.class object (or foo.getClass().getDeclaredFields() if you have the class instance in hand.

getDeclaredFields() returns an array of Field object (declared in java.lang.reflect package).

It seems that you want to work with the object in database, so it might be good to take a look at Java Persistence API instead of generating INSERT statements manually as that will provide you so much more and not having to work so much manually on SQL.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜