웹 개발

[java] dynamic getter, setter

노루아부지 2019. 7. 18. 19:13

개발을 하다보면 부득이하게 동적으로 class에 값을 넣거나 값을 가져와야 할 경우가 있습니다.

아래와 같이 class.getDeclaredField() 를 사용하면 손쉽게 할 수 있습니다.

 

 

public class TAllSaveThsusBean {
 
    /**
     * Desc : Refection을 활용한 Getter/Setter
     */
    public ArrayList<Object> ReflectionGF(ArrayList<Object> objAL) throws Exception {
        try {
            //VALL 객체 : Value Object로 Getter, Setter를 가지고 있음 
            VALL v_condition        = 화면에서 넘겨 받은 값 VO : 조건값
            ArrayList<VALL> v_save1 = 화면에서 넘겨 받은 값 VO : 저장할 VO이면서 여러레코드를 가지고 있음 
            
            String sPrimaryKey  = v_condition.getPrimaryKey();  /* VO에서 Getter할 Method명인 String문자열 */
            String sPrimaryKey1 = v_condition.getPrimaryKey1(); /* VO에서 Getter할 Method명인 String문자열 */
            String sPKVal  = refGet(v_save1, sPrimaryKey ); /* sPrimaryKey 문자열 해당 하는 Getter명의 값을 얻기*/
            String sPKVal1 = refGet(v_save1, sPrimaryKey1); /* sPrimaryKey1문자열 해당 하는 Getter명의 값을 얻기 */
            
            VALL v_one = v_save1.get(0);
            
            refSet(v_one, sPrimaryKey , sPKVal);
            refSet(v_one, sPrimaryKey1, sPKVal1);
                    
            return null;
            
        } catch (Exception e) {
            ctx.setRollbackOnly();
            throw new Exception(e);
        }
    }
 
    /**
     * Desc : 넘겨받은 문자열(fieldName)에 해당 되는 -> Object(VO)의 값을 얻기   
     */
    @SuppressWarnings("unchecked")
    public static <E> E refGet(Object object, String fieldName) {
        Class<?> class = object.getClass();
        while (class != null) {
            try {
                Field field = class.getDeclaredField(fieldName);
                field.setAccessible(true);
                return (E) field.get(object);
            } catch (NoSuchFieldException e) {
                class = class.getSuperclass();
            } catch (Exception e) {
                throw new IllegalStateException(e);
            }
        }
        return null;
    }
 
    /**
     * Desc : 넘겨받은 문자열(fieldName)에 해당 되는  변수에   값(filedvalue)을 -> Object(VO)에 넣기   
     */
    @SuppressWarnings("rawtypes")
    public static boolean refSet(Object object, String fieldName, Object fieldValue) {
        Class class = object.getClass();
        while (class != null) {
            try {
                Field field = class.getDeclaredField(fieldName);
                field.setAccessible(true);
                field.set(object, fieldValue);
                return true;
            } catch (NoSuchFieldException e) {
                class = class.getSuperclass();
            } catch (Exception e) {
                throw new IllegalStateException(e);
            }
        }
        return false;
    }
}

 

 

출처 : https://m.blog.naver.com/PostView.nhn?blogId=joypheonix&logNo=100163503643&proxyReferer=https%3A%2F%2Fwww.google.com%2F

728x90
loading