티스토리 뷰

Studying/Web Application

Reflection 정리

hongkyu 2012. 10. 10. 08:28

1.      Constructor, Field, Method 분석

reflection을 사용하여 주어진 reflection.ReflectionVO 클래스의 Constructor, Field, Method를 분석하여 System.out으로 출력하는 로직을 작성하시오.

 

1) 소스

 

public void reflection_1() {

        Class clazz = ReflectionVO.class;

       

        // 1. Constructor 분석

        Constructor[] constructors = clazz.getDeclaredConstructors();

        System.out.println("==== Constructor(생성자) 분석 ====");

       

        for(int i=0; i<constructors.length; i++) {

               System.out.print((i+1) + ". ");

              

               // 1.1 접근제어자 출력

               System.out.print(Modifier.toString(constructors[i].getModifiers()));

               System.out.print(" ");

              

               // 1.2 Constructor 명 출력

               System.out.print(constructors[i].getDeclaringClass().getSimpleName());

                                     

               // 1.3 파라미터 타입 출력

               Class[] parameterTypes = constructors[i].getParameterTypes();

               System.out.print(" (");

               for(int j=0; j<parameterTypes.length; j++) {

                       if(j!=0){

                              System.out.print(", ");

                       }

                       System.out.print(parameterTypes[j].getSimpleName());

               }

               System.out.println(")");

        }

       

        // 2. Field 분석

        Field[] fields = clazz.getDeclaredFields();

        System.out.println("==== Field(맴버변수) 분석 ====");

       

        for(int i=0; i<fields.length; i++) {

               System.out.print((i+1) + ". ");

              

               // 2.1 접근제어자 출력

               System.out.print(Modifier.toString(fields[i].getModifiers()));

               System.out.print(" ");

                                     

               // 2.2 Field 타입 출력

               System.out.println(fields[i].getType().getSimpleName());

        }

       

        // 3. Method 분석

        Method[] methods = clazz.getDeclaredMethods();

        System.out.println("==== Method(맴버함수) 분석 ====");

       

        for(int i=0; i<methods.length; i++) {

               System.out.print((i+1) + ". ");

 

               // 3.1 접근제어자 출력

               System.out.print(Modifier.toString(methods[i].getModifiers()));

               System.out.print(" ");

                                     

               // 3.2 Return 타입 출력

               System.out.print(methods[i].getReturnType().getSimpleName());

               System.out.print(" ");

              

               // 3.3 Method 명 출력

               System.out.print(methods[i].getName());

              

               // 3.4 파라미터 타입 출력

               Class[] parameterTypes = methods[i].getParameterTypes();

               System.out.print(" (");

               for(int j=0; j<parameterTypes.length; j++) {

                       if(j!=0){

                              System.out.print(", ");

                       }

                       System.out.print(parameterTypes[j].getSimpleName());

               }

               System.out.println(")");

        }

}

 

 

2) 실행 결과

 

==== Constructor(생성자) 분석 ====

1. public ReflectionVO (String)

2. public ReflectionVO ()

3. public ReflectionVO (String, int)

4. public ReflectionVO (String, int, double)

==== Field(맴버변수) 분석 ====

1. private String

2. private int

3. private double

==== Method(맴버함수) 분석 ====

1. public void setStringField (String)

2. public void setIntField (int)

3. public void setDoubleField (double)

4. public String getStringField ()

5. public int getIntField ()

6. public double getDoubleField ()

7. public String toString ()

8. public void print ()

 

 

2.      클래스의 객체 동적 생성

reflection을 사용하여 주어진 reflection.ReflectionVO 클래스의 객체를 동적으로 생성하는 로직을 작성하시오. (주어진 클래스의 생성자(Constructor) 4개이므로, 각각 작성해야 함.)

 

1) 소스

 

public void reflection_2() throws Exception {

       

        Class clazz = ReflectionVO.class;

       

        // 1. 생성자 ReflectionVO() 을 사용

        System.out.println("==== ReflectionVO() ====");

       

        Constructor constructor_1 = clazz.getDeclaredConstructor();

        Object reflectioVO_1 = (ReflectionVO)constructor_1.newInstance();

       

        System.out.println(reflectioVO_1.toString());

       

        // 2. 생성자 ReflectionVO(String stringField) 을 사용

        System.out.println("==== ReflectionVO(String stringField) ====");

       

        Constructor constructor_2 = clazz.getDeclaredConstructor(String.class);

        Object reflectioVO_2 = (ReflectionVO)constructor_2.newInstance("SAMPLE_TEST");

       

        System.out.println(reflectioVO_2.toString());

       

        // 3. 생성자 ReflectionVO(String stringField, int intField) 을 사용

        System.out.println("==== ReflectionVO(String stringField, int intField) ====");

       

        Constructor constructor_3 = clazz.getDeclaredConstructor(String.class, int.class);

        Object reflectioVO_3 = (ReflectionVO)constructor_3.newInstance("SAMPLE_TEST", 9999);

       

        System.out.println(reflectioVO_3.toString());

       

        // 4. 생성자 ReflectionVO(String stringField, int intField, double doubleField) 을 사용

        System.out.println("==== ReflectionVO(String stringField, int intField, double doubleField) ====");

       

        Constructor constructor_4 = clazz.getDeclaredConstructor(String.class, int.class, double.class);

        Object reflectioVO_4 = (ReflectionVO)constructor_4.newInstance("SAMPLE_TEST", 9999, 10.01);

       

        System.out.println(reflectioVO_4.toString());

       

}

 

 

2) 실행 결과

 

==== ReflectionVO() ====

stringField=null, intField=0, doubleField=0.0

==== ReflectionVO(String stringField) ====

stringField=SAMPLE_TEST, intField=0, doubleField=0.0

==== ReflectionVO(String stringField, int intField) ====

stringField=SAMPLE_TEST, intField=9999, doubleField=0.0

==== ReflectionVO(String stringField, int intField, double doubleField) ====

stringField=SAMPLE_TEST, intField=9999, doubleField=10.01

 

 

3.      필드값 설정

reflection을 사용하여 2번에서 동적으로 생성한 객체의 각각의 필드값을 설정하는 로직을 작성하시오.

 

1) 소스

 

public void reflection_3() throws Exception {

       

        Class clazz = ReflectionVO.class;

       

        // 1. ReflectionVO 생성              

        Constructor constructor = clazz.getDeclaredConstructor();

        Object reflectioVO = (ReflectionVO)constructor.newInstance();

       

        System.out.println("==== 필드값 설정 전 ====");

        System.out.println(reflectioVO.toString());

       

        // 2. 필드값 설정

        // 2.1 필드 객체 가져오기

        Field stringField = clazz.getDeclaredField("stringField");

        Field intField = clazz.getDeclaredField("intField");

        Field doubleField = clazz.getDeclaredField("doubleField");

       

        // 2.2 필드 Accessible 상태 변경            

        stringField.setAccessible(true);

        intField.setAccessible(true);

        doubleField.setAccessible(true);

       

        // 2.3 필드 값 설정          

        stringField.set(reflectioVO, "SAMPLE_TEST");

        intField.set(reflectioVO, 9999);

        doubleField.set(reflectioVO, 10.01);

       

        System.out.println("==== 필드값 설정 후 ====");

        System.out.println(reflectioVO.toString());         

}

 

 

2) 실행 결과

 

==== 필드값 설정 전 ====

stringField=null, intField=0, doubleField=0.0

==== 필드값 설정 후 ====

stringField=SAMPLE_TEST, intField=9999, doubleField=10.01

 

 

4.      필드값 조회

reflection을 사용하여 3번의 객체에서 각각의 필드값을 조회하는 로직을 작성하시오.

 

1) 소스

 

public void reflection_4() throws Exception {

       

        Class clazz = ReflectionVO.class;

       

        // 1. ReflectionVO 생성              

        Constructor constructor = clazz.getDeclaredConstructor();

        Object reflectioVO = (ReflectionVO)constructor.newInstance();

       

        System.out.println("==== 필드값 설정 전 ====");

        System.out.println(reflectioVO.toString());

       

        // 2. 필드값 설정

        // 2.1 필드 객체 가져오기

        Field stringField = clazz.getDeclaredField("stringField");

        Field intField = clazz.getDeclaredField("intField");

        Field doubleField = clazz.getDeclaredField("doubleField");

       

        // 2.2 필드 Accessible 상태 변경            

        stringField.setAccessible(true);

        intField.setAccessible(true);

        doubleField.setAccessible(true);

       

        // 2.3 필드 값 설정          

        stringField.set(reflectioVO, "SAMPLE_TEST");

        intField.set(reflectioVO, 9999);

        doubleField.set(reflectioVO, 10.01);

       

        System.out.println("==== 필드값 설정 후 ====");

        System.out.println(reflectioVO.toString());

       

       

        // 3. 필드값 조회

        System.out.println("==== 필드값 조회 ====");

        System.out.println("stringField : " + stringField.get(reflectioVO));

        System.out.println("intField : " + intField.get(reflectioVO));

        System.out.println("doubleField : " + doubleField.get(reflectioVO));

}

 

 

2) 실행 결과

 

==== 필드값 설정 전 ====

stringField=null, intField=0, doubleField=0.0

==== 필드값 설정 후 ====

stringField=SAMPLE_TEST, intField=9999, doubleField=10.01

==== 필드값 조회 ====

stringField : SAMPLE_TEST

intField : 9999

doubleField : 10.01

 

 

5.      commons-beanutils

reflection을 지원하는 대표적인 오픈소스인 commons-beanutils의 특징을 간략히 기술하고, beanutils을 사용하여 3,4번을 위한 로직을 작성하시오.

 

1) commons-beanutils의 특징

  commons-beanutilsReflectionIntrospection 개념을 적용하고 있는 이 Apache Commons Library로서, Bean 클래스를 wrapping하여 Bean interface를 동적으로 파악, 처리할 수 있고, Bean 클래스를 직접 작성하지 않고 동적인 Bean 형태로 프로그래밍할 수 있는 기능도 지원한다.

 

2) 소스

 

public void reflection_5() throws Exception {

       

        // 1. 필드 값을 담고 있는 Map 생성

        Map insertMap = new HashMap();

       

        insertMap.put("stringField", "SAMPLE_TEST");

        insertMap.put("intField", 9999);

        insertMap.put("doubleField", 10.01);

       

        // 2. ReflectionVO 생성 및 필드값 셋팅

        System.out.println("==== ReflectionVO 생성 및 필드값 셋팅 ====");

       

        Object reflectionVO = ReflectionVO.class.newInstance();

        BeanUtils.populate(reflectionVO, insertMap);

       

        System.out.println(reflectionVO.toString());

       

        // 3. ReflectionVO 필드값 조회

        System.out.println("==== ReflectionVO 필드값 조회 ====");

       

        Map resultMap = BeanUtils.describe(reflectionVO);

       

        System.out.println("stringField : " + resultMap.get("stringField"));

        System.out.println("intField : " + resultMap.get("intField"));

        System.out.println("doubleField : " + resultMap.get("doubleField"));              

}

 

 

3) 실행 결과

 

==== ReflectionVO 생성 및 필드값 셋팅 ====

stringField=SAMPLE_TEST, intField=9999, doubleField=10.01

==== ReflectionVO 필드값 조회 ====

stringField : SAMPLE_TEST

intField : 9999

doubleField : 10.01

 

 

반응형

'Studying > Web Application' 카테고리의 다른 글

WebLogic 관리자 패스워드 초기화  (0) 2012.11.05
MappingJacksonJsonView Map 변환  (0) 2012.10.30
XML Parser 정리  (0) 2012.10.10
DB Connection 정리  (0) 2012.10.10
Apache Commons Logging  (0) 2012.10.10
댓글
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
최근에 올라온 글
글 보관함
Total
Today
Yesterday