如何获得的列表中的所有属性的一个Java对象使用BeanUtils反思?
-
10-07-2019 - |
题
我有方法让一个只因为它的参数。现在我想编程方式获得的所有属性的组(因为我的代码可能不知道什么是所有的属性,它在运行时间),并需要获得值的属性。最后我就会形成一串的代表组成。
我可以用 ToStringBuilder, 但是我想建立我的输出串在一定的格式具体到我的要求。
是否有可能这样做Beanutils!?如果是,任何指针的方法的名字吗?如果没有,我应该编写自己的反射代码?
解决方案
您是否尝试过的 ReflectionToStringBuilder ?这貌似是应该做你的描述。
其他提示
我知道这是一岁多的问题,但我认为它可以成为有用的人。
我已经发现使用此LOC的部分解决方案
Field [] attributes = MyBeanClass.class.getDeclaredFields();
下面是一个工作示例:
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();
}
}
}
}
得到所有属性/变量(只有名称)使用的反思。现在使用的 getProperty 法得到价值的变量
不隶属于 StackOverflow