본문 바로가기
카테고리 없음

[Java] 자바 클래스에서 Getter 메소드 얻어오기 (Introspector)

by 왕 달팽이 2019. 6. 19.
반응형

자바 객체를 이용해서 데이터를 주고 받을 때, 객체 클래스의 Getter 메소드를 호출해야하는 경우가 있다. 특정 객체 클래스의 Getter 메소드를 리플렉션(Reflection)을 이용해서 가져올 수도 있지만 전달하는 객체가 자바빈 객체라면 다음 코드를 사용할 수도 있다.


import java.beans.Introspector;
import java.beans.PropertyDescriptor;

public class Example {

    private String name;

    private String address;

    public String getName() {
        return name;
    }

    public String getAddress() {
        return address;
    }

    public String getABC(String a) {
        return name + a;
    }

    public static void main(String []args) throws Exception {

        for (PropertyDescriptor propertyDescriptor : Introspector.getBeanInfo(Example.class).getPropertyDescriptors()) {
            System.out.println(propertyDescriptor.getReadMethod());
        }
    }
}

이 코드의 실행 결과는 다음과 같다.

public java.lang.String feeden.Example.getAddress()
public final native java.lang.Class java.lang.Object.getClass()
public java.lang.String feeden.Example.getName()

getABC(String a) 메소드는 getter 메소드 정의에 맞지 않기 때문에 결과에서 빠졌다. getBeanInfo() 메소드에 두 번째 인자를 주면, 첫 번째 인자의 getter 메소드에서 두 번째 인자의 getter 메소드를 제외한다.

getBeanInfo(Example.class, Object.class)라고 코드를 수정하면, Example.class의 getter 메소드 중 Object 클래스에서 정의된 메소드는 제외한다. 즉 다음과 같은 결과를 얻을 수 있다.

public java.lang.String feeden.Example.getAddress()
public java.lang.String feeden.Example.getName()

BeanUtils 프레임워크

BeanUtils라는 프레임 워크를 사용할 수도 있다.

Map<String, String> properties = BeanUtils.describe(<your object>);

다음 코드를 실행해보자.

import org.apache.commons.beanutils.BeanUtils;

import java.util.Map;

public class Example {

    private String name;

    private String address;

    public Example(String name, String address) {
        this.name = name;
        this.address = address;
    }

    public String getName() {
        return name;
    }

    public String getAddress() {
        return address;
    }

    public String getABC(String a) {
        return name + a;
    }

    public static void main(String []args) throws Exception {

        Example example = new Example("newName", "new Address");

        Map<String, String> properties = BeanUtils.describe(example);

        for (String key : properties.keySet()) {
            System.out.println("key=" + key + ", value=" + properties.get(key));
        }
    }
}

이를 실행시키면

key=address, value=new Address
key=name, value=newName
key=class, value=class feeden.Example

이와 같은 결과를 얻을 수 있다.

반응형

댓글