如何使用BeanUtils内省获取Java对象的所有属性列表?

Vee*_*era 13 java reflection introspection apache-commons-beanutils

我有一个获取POJO作为参数的方法.现在我想以编程方式获取POJO的所有属性(因为我的代码可能不知道运行时它的所有属性是什么),并且还需要获取属性的值.最后,我将形成POJO的字符串表示.

我可以使用ToStringBuilder,但我希望以特定于我的要求的特定格式构建输出字符串.

是否有可能在Beanutils中这样做?如果是,任何指向方法名称的指针?如果不是,我应该编写自己的反射代码吗?

Jor*_*cio 16

我知道这是一个有问题的问题,但我认为这对其他人有用.

我找到了使用这个LOC的部分解决方案

Field [] attributes =  MyBeanClass.class.getDeclaredFields();
Run Code Online (Sandbox Code Playgroud)

这是一个工作示例:

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();
            }

        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Joh*_*her 10

你试过ReflectionToStringBuilder吗?它看起来应该做你所描述的.

  • 链接丢失了! (2认同)