java 在java中迭代对象属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7467936/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Iterate over object attributes in java
提问by tgm
Possible Duplicate:
How to loop over a Class attributes in Java?
可能的重复:
如何在 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.
有没有办法在java中迭代这个对象属性?我想创建一个 INSERT 查询,我必须转换字符串中的所有 int 属性。当不同类型的属性较多时,这有点问题。
Thanks!
谢谢!
回答by Jayendra
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/
应该使用反射返回类的所有声明字段。更多信息@ http://java.sun.com/developer/technicalArticles/ALT/Reflection/
回答by npinti
回答by Thomas
If the order of the properties is not relevant use Apache Commons BeanUtils:
如果属性的顺序不相关,请使用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.
请注意,BeanUtils
不使用泛型,因此是强制转换。
Additional note: your objects have to adhere to the JavaBeans specification in order to use this approach.
附加说明:您的对象必须遵守 JavaBeans 规范才能使用此方法。
回答by Saket
You can use Java Reflection to do so.
您可以使用 Java 反射来做到这一点。
回答by Jari
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.
您可以通过调用 Foo.class 对象(或 foo.getClass().getDeclaredFields() 如果手头有类实例)上的 getDeclaredFields() 方法来获取 Foo 类的所有字段。
getDeclaredFields() returns an array of Field object (declared in java.lang.reflect package).
getDeclaredFields() 返回一个 Field 对象数组(在 java.lang.reflect 包中声明)。
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.
似乎您想使用数据库中的对象,因此最好查看 Java Persistence API 而不是手动生成 INSERT 语句,因为这将为您提供更多功能,而不必在 SQL 上手动操作太多.