我知道这是一个已经存在了一年的问题,但我认为它对其他人有用。
我已使用此 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();
}
}
}
}