如何使用 BeanUtils 自省获取 Java 对象的所有属性列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1038308/
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
How to get the list of all attributes of a Java object using BeanUtils introspection?
提问by Veera
I have method which gets a POJO as it's parameter. Now I want to programmatically get all the attributes of the POJO (because my code may not know what are all the attributes in it at run time) and need to get the values for the attributes also. Finally I'll form a string representation of the POJO.
我有获取 POJO 作为参数的方法。现在我想以编程方式获取 POJO 的所有属性(因为我的代码在运行时可能不知道其中的所有属性是什么)并且还需要获取属性的值。最后,我将形成 POJO 的字符串表示形式。
I could use ToStringBuilder, but I want build my output string in certain format specific to my requirement.
我可以使用ToStringBuilder,但我想以特定于我的要求的特定格式构建我的输出字符串。
Is it possible to do so in Beanutils !? If yes, any pointers to the method name? If no, should I write my own reflection code?
在 Beanutils 中可以这样做吗!?如果是,任何指向方法名称的指针?如果不是,我应该编写自己的反射代码吗?
采纳答案by John Meagher
Have you tried ReflectionToStringBuilder? It looks like is should do what you describe.
你试过ReflectionToStringBuilder吗?看起来应该按照你的描述做。
回答by Rakesh Juyal
get all properties/variables ( just the name ) using reflection. Now use getPropertymethod to get the value of that variable
使用反射获取所有属性/变量(只是名称)。现在使用getProperty方法获取该变量的值
回答by Jorge Palacio
I know this is a year old question, but I think it can be useful for others.
我知道这是一个古老的问题,但我认为它对其他人有用。
I have found a partial solution using this LOC
我找到了使用此 LOC 的部分解决方案
Field [] attributes = MyBeanClass.class.getDeclaredFields();
Here is a working example:
这是一个工作示例:
import java.lang.reflect.Field;
import org.apache.commons.beanutils.PropertyUtils;
public class ObjectWithSomeProperties {
private String firstProperty;
private String secondProperty;
public String getFirstProperty() {
return firstProperty;
}
public void setFirstProperty(String firstProperty) {
this.firstProperty = firstProperty;
}
public String getSecondProperty() {
return secondProperty;
}
public void setSecondProperty(String secondProperty) {
this.secondProperty = secondProperty;
}
public static void main(String[] args) {
ObjectWithSomeProperties object = new ObjectWithSomeProperties();
// Load all fields in the class (private included)
Field [] attributes = object.getClass().getDeclaredFields();
for (Field field : attributes) {
// Dynamically read Attribute Name
System.out.println("ATTRIBUTE NAME: " + field.getName());
try {
// Dynamically set Attribute Value
PropertyUtils.setSimpleProperty(object, field.getName(), "A VALUE");
System.out.println("ATTRIBUTE VALUE: " + PropertyUtils.getSimpleProperty(object, field.getName()));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}