Beanutils 내성을 사용하여 Java 객체의 모든 속성 목록을 얻는 방법은 무엇입니까?

StackOverflow https://stackoverflow.com/questions/1038308

문제

Pojo를 매개 변수로 얻는 방법이 있습니다. 이제 Pojo의 모든 속성을 프로그래밍 방식으로 얻고 싶습니다 (내 코드는 실행 시간에 모든 속성이 무엇인지 알 수 없기 때문에) 속성의 값도 가져와야합니다. 마지막으로 Pojo의 문자열 표현을 형성하겠습니다.

나는 사용할 수있다 TostringBuilder, 그러나 요구 사항에 맞는 특정 형식으로 출력 문자열을 빌드하고 싶습니다.

Beanutils에서 그렇게 할 수 있습니까!? 그렇다면 메소드 이름에 대한 포인터가 있습니까? 아니오라면 내 자신의 반사 코드를 작성해야합니까?

도움이 되었습니까?

해결책

당신은 시도 했습니까? 반사 변환 빌더? 그것은 당신이 묘사하는 일을 해야하는 것처럼 보입니다.

다른 팁

나는 이것이 1 년 된 질문이라는 것을 알고 있지만 다른 사람들에게 유용 할 수 있다고 생각합니다.

이 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 해당 변수의 값을 얻는 방법

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top