본문 바로가기

프로그램/java

Bean 정보를 읽어 멤버변수를 반환하게 하는 클래스

반응형
PropertyDescriptor 클래스를 이용하여 Bean 내용을 읽어 setXXX, getXXX 중 한개라도 메서드가 존재하는
멤버변수 값을 받아오는 클래스를 작성해 보았다.

또한 해당 Member 변수에 담긴 값도 알아올 수 있었다.
(다만 setter 가 실행되지 않게 되면 값이 할당되지 않아 null이 ㅂ

Java 환경에서 수행하였기에 PropertyDescriptor 를 얻어오는 방법으로
Instrospector 클래스와 BeanInfo 클래스를 사용하였다.

만약 웹 환경이라면 아차피 홈페이지에서 받은 Commons-beanutils.jar를 이용하여
다음과 같이 코딩하면 되겠다.

PropertyDescriptor[] descriptor = PropertyUtils.getPropertyDescriptors(obj);

참고url로
http://blog.naver.com/estern/110007148167
를 참고하였다.


소스는 다음고 같다.

package propertyDescriptor;

/**
 * 빈 정보를 propertyDescriptor 를 얻을 때 사용할 bean
 * userName, userEmail 정보를 가지고 있음
 * @author lsk
 * @since 2009.07.06
 */
public class ExBean {
    private String userName;
    private String userEmail;
   
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getUserEmail() {
        return userEmail;
    }
    public void setUserEmail(String userEmail) {
        this.userEmail = userEmail;
    }
}


package propertyDescriptor;

import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * ExBean의 정보를 가져와서 보여줄 클래스
 * @author lsk
 * @since 2009.07.06
 */
public class ExBeanInfo {
//    public static void main(String[] args) {
//        ExBeanInfo exBeanInfo = new ExBeanInfo();
//       
//        exBeanInfo.print();
//    }
   
    /**
     * 기본생성자
     */
    public ExBeanInfo() {
    }
   
    /**
     * bean의 property 의 이름을 String배열로 넘김
     * @param bean
     * @return bean의 이름을 담고있는 String 배열
     * @throws IntrospectionException
     */
    public String[] getPropertyNameList(Object bean) throws IntrospectionException {
        PropertyDescriptor descriptor[] = (Introspector.getBeanInfo(bean.getClass())).getPropertyDescriptors();
       
        String[] rtnStr = new String[descriptor.length];
       
        for(int i=0; i<descriptor.length; i++) {
            rtnStr[i] = descriptor[i].getName();
        }
       
        return rtnStr;
       
    }
   
    /**
     * bean의 property 의 값을 Object배열로 넘김
     * @param bean
     * @return bean의 이름을 담고있는 Object 배열
     * @throws IntrospectionException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     */
    public Object[] getPropertyValueList(Object bean) throws IntrospectionException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
        PropertyDescriptor descriptor[] = (Introspector.getBeanInfo(bean.getClass())).getPropertyDescriptors();
       
        Object[] rtnObj = new Object[descriptor.length];
        Method method = null;
       
        for(int i=0; i<descriptor.length; i++) {
            method = descriptor[i].getReadMethod();
           
            if(method != null) {
                rtnObj[i] = method.invoke(bean, new Object[0]);
            }
        }
       
        return rtnObj;
    }
   
//    public void print() {
//        ExBean exBean = new ExBean();
//       
//        exBean.setUserName("LeeSeungKyu");
//        exBean.setUserEmail("idmakeh@naver.com");
//       
//        try {
//            BeanInfo beanInfo = Introspector.getBeanInfo(exBean.getClass());
//            PropertyDescriptor descriptor[] = beanInfo.getPropertyDescriptors();
//           
//            Map<String, Object> map = new HashMap<String, Object>();
//           
//            Object value = null;
//           
//            for(int i=0; i<descriptor.length; i++) {
//                Method read = descriptor[i].getReadMethod();
//                if(read != null) {
//                    value = read.invoke(exBean, new Object[0]);
//                }
//                map.put(descriptor[i].getName(), value);
//            }
//           
//            Set<String> key = map.keySet();
//           
//            for(String keyName : key) {
//                System.out.println("keyName : " + keyName);
//                System.out.println("value : " + map.get(keyName));
//            }
//        } catch (IntrospectionException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        } catch (IllegalArgumentException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        } catch (IllegalAccessException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        } catch (InvocationTargetException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
//    }
}


package propertyDescriptor;

import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;

/**
 * bean의 property 정보를 가져오는 main함수
 * @author 이승규
 * @since 2009.07.06
 */
public class ExBeanMain {
    public static void main(String[] args) {
        ExBean exBean = new ExBean();
       
        // settter을 실행하지 않으면 value값이 null로 넘어온다.
//        exBean.setUserName("LeeSeungKyu");
        exBean.setUserEmail("idmakeh@naver.com");
       
        try {
            String[] rtnStr = (new ExBeanInfo()).getPropertyNameList(exBean);        // bean의 property name
            Object[] rtnStr2 = (new ExBeanInfo()).getPropertyValueList(exBean);        // bean의 property value
           
            // 넘겨받은 name 출력
            if(rtnStr != null) {
                for(int i=0; i<rtnStr.length; i++) {
                    System.out.println("keyName[" + i + "] : " + rtnStr[i]);
                }
            }
           
            // 넘겨받은 value 출력
            if(rtnStr2 != null) {
                for(int i=0; i<rtnStr2.length; i++) {
                    System.out.println("value[" + i + "] : " + rtnStr2[i]);
                }
            }
        } catch (IntrospectionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

2012.03.06 추가
set을 해야 할 경우 
method = descriptor[i].getWriteMethod();
로 method를 구해온 후 

method.invoke(bean, objArr[i]);

PropertyDescriptor 를 구해와서 보면 알파벳 오름차순 순서임
그리고 getClass 때문에 class값이 포함되어 있을 수 있으니

이를 고려해야 함