SlideShare a Scribd company logo
THE SYS4U DODUMENT


Java Reflection & Introspection




                                  2012.08.21




                                                                    김진아 사원
                                               © 2012 SYS4U I&C All rights reserved.
목차
I.    개념                                     Ⅲ. 관련 라이브러리
       1. Reflection 이란?
       2. Introspection 이란?                     1.    Commons.BeanUtils
       3. Reflection 과 Introspection 의 차이점
                                             Ⅳ. Q&A
II.   실제 사용 예
       1. Instance의 생성
       2. Class Type 생성
       3. Instanceof 대체 Reflection API
       4. Class의생성자의 정보 얻기
       5. Class의 Field 얻기
       6. Class의 Method 얻기
       7. Method의 이름으로 Method 실행하기
       8. Field값 변경
       9. 배열에서의 사용
       10. Reflection을 이용한 Factory pattern




                                                                          THE SYS4U PAPER 2012 |   2
I. 개념




        THE SYS4U PAPER 2012 |   3
I. Reflection 이란?                   Ⅰ. 개념




 Java.lang.reflect 패키지 사용




 클래스 인스턴스로부터 그 인스턴스가 표현하는 멤버, 필드, 메소드에 접근할 수 있는 기능




 클래스 구조에 대한 정보 뿐만 아니라 객체의 생성, 메소드 호출, 필드 접근까지 가능




                                              THE SYS4U PAPER 2012 |   4
Ⅱ. Introspection 이란?                 Ⅰ. 개념




 빈의 프로퍼티와 메소드 등을 알려주기 위해 빈의 디자인 패턴을 자동으로 분석하는 과정




 객체의 클래스, 구현 메소드, 필드 등의 객체정보를 조사하는 과정을 의미




                                              THE SYS4U PAPER 2012 |   5
Ⅲ. Reflection 과 Introspection의 차이점                Ⅰ. 개념



                                     Reflection




                                     조작
                 Introspection


                   조사


                                                          THE SYS4U PAPER 2012 |   6
Ⅱ. 실제 사용 예




             THE SYS4U PAPER 2012 |   7
Ⅰ. Instance의 생성 (1/3)                                             Ⅱ. 실제 사용 예

• new
  public class Sample {

      private void outputMessage(){

              System.out.println("outputMessage");
      }

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

              Sample sample1 = new Sample();
              sample1.outputMessage();
      }
  }


• 실행결과

 outputMessage



                                                                               THE SYS4U PAPER 2012 |   8
Ⅰ. Instance의 생성 (2/3)                                                 Ⅱ. 실제 사용 예

• clone
  public class Sample implements Cloneable{

          private void outputMessage(){

                  System.out.println("outputMessage");
          }

          public static void main(String[] args) throws Exception {
                Sample sample1 = new Sample();
                Sample sample3 = (Sample) sample1.clone();
                sample3.outputMessage();
      }
  }


• 실행결과

 outputMessage



                                                                                   THE SYS4U PAPER 2012 |   9
Ⅰ. Instance의 생성 (3/3)                                             Ⅱ. 실제 사용 예

• Class<T>.newInstance
  public class Sample {

      private void outputMessage(){

              System.out.println("outputMessage");
      }

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

            Class c = Class.forName("Sample");
            Sample sample2 = c.newInstance();
            sample2.outputMessage();
      }
  }

• 실행결과

 outputMessage



                                                                               THE SYS4U PAPER 2012 |   10
Ⅱ. Class Type 생성                                     Ⅱ. 실제 사용 예




public static void main(String[] args) {
     Class c1 = Class.forName("java.lang.String");
}




public static void main(String[] args) {
     Class<Integer> c2 = int.class;
}




public static void main(String[] args) {
     Class<Integer> c3 = Integer.TYPE;
}



                                                                  THE SYS4U PAPER 2012 |   11
Ⅲ. Instanceof 대체 Reflection API                                   Ⅱ. 실제 사용 예


  public class A {

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

            Class c = Class.forName("A");

            boolean b1 = c.isInstance(new Integer(65));
            System.out.println("new Integer(65) == > "+b1);


            boolean b2 = c.isInstance(new A());
            System.out.println("new A()      == > "+b2);
      }
  }


 • 실행결과

 new Integer(65) == > false
 new A()         == > true



                                                                               THE SYS4U PAPER 2012 |   12
Ⅳ. Class의 생성자의 정보 얻기                                                          Ⅱ. 실제 사용 예


 public class Const {

         public Const(int i, String str){ }
     •    실행결과
         public static void main(String[] args) throws Exception{

             Class c= Class.forName("Const");

        Constructor constList[] = c.getDeclaredConstructors();
 Class Name         : class Const
 Constructor Name : i < constList.length; i++) {
        for (int i = 0; Const
 ------------------------------------------------
           Constructor constructor = constList[i];
 param 0 :System.out.println("Class Name
              int                                 : " + constructor.getDeclaringClass());
              class out.println("Constructor Name : "+ constructor.getName());
 param 1 :System.java.lang.String
           System.out.println("------------------------------------------------");

                 Class param[] = constructor.getParameterTypes();
                 for (int j = 0; j < param.length; j++) {
                    System.out.println("param "+ j +" : “ + param[ j]);
                 }
             }
         }
 }


                                                                                            THE SYS4U PAPER 2012 |   13
Ⅴ. Class Field 얻기                                                                Ⅱ. 실제 사용 예


  public class F {

     private int a;
     public static final String b="b";
     double c;
  Class : class F
  Field Name : a void main(String[] args) throws Exception {
     public static
  Field Type : int
  Field Modifiers : private
          Class cls = Class.forName(“F");
  -------------------------------------------------
  Class : Field fieldList[] = c.getDeclaredFields();
          class F
  Field Name : b
  Field Type (int i =java.lang.String
          for : class 0; i < fieldList.length; i++) {
  Field Modifiers : public static final
             Field field = fieldList[i];
  -------------------------------------------------
  Class : class F out.println("Class : " + field.getDeclaringClass());
             System.
  Field Name : c out.println("Field Name : " + field.getName());
             System.
             System.out.
  Field Type : double println("Field Type : " + field.getType());
  Field Modifiers : out.println("Field Modifiers : " + Modifier.toString(field.getModifiers()));
             System.
             System.out.println("-------------------------------------------------");
  -------------------------------------------------

           }
       }
   }


                                                                                                   THE SYS4U PAPER 2012 |   14
Ⅵ. Class의 Method 얻기                                                                          Ⅱ. 실제 사용 예

  public class M {
   private int test(String str,int i) throws NullPointerException{
        if(str ==null || str.equals("")) { throw new NullPointerException();             }
        return -1;
    }
  public static void main(String[] args) throws Exception {
      Class cls : Class.forName(“M");
  Class Name = class M
  Method Name : main = c.getDeclaredMethods();
      Method methodList[]
  Param 0 : class [Ljava.lang.String;
      for (int i = 0; i < methodList.length; i++) {
  exc 0 : class java.lang.Exception
         Method method = methodList[i];
  ReturnType : void
         System.out.println("Class Name : " + method.getDeclaringClass());
  ------------------------------------------------method.getName());
         System.out.println("Method Name : "+
  Class Name : class M
  Method Name : test = method.getParameterTypes();
         Class paramList[]
  Param 0 for (int java.lang.String
            : class j = 0; j < paramList.length; j++) {
  Param 1 : int System.out.println("Param " + j + " : " + paramList[ j]);            }
  exc 0 : class java.lang.NullPointerException
  ReturnType excList[]= method.getExceptionTypes();
         Class : int
  ------------------------------------------------ {
            for (int j = 0; j < excList.length; j++)
                System.out.println("exc " + j + " : " + excList[ j]);     }

           System.out.println("ReturnType : " + method.getReturnType());
           System.out.println("------------------------------------------------");
       }
   }

                                                                                                          THE SYS4U PAPER 2012 |   15
Ⅶ. Method의 이름으로 Method 실행하기 (1/2)                                    Ⅱ. 실제 사용 예

public class A {
        public int add(int a, int b) { return a+b; }           •   실행결과
}

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

        Class c = Class.forName(“A");

        Class param[] = new Class[2];
        param[0] = Integer.TYPE;
        param[1] = Integer.TYPE;

        Method method = c.getDeclaredMethod("add", param);                  2
        A a = new A();
        Object argList[] = new Object[2];
        argList[0] = new Integer(1);
        argList[1] = new Integer(1);
        Object obj = method.invoke(a, argList);
        Integer value = (Integer) obj;

        System.out.println(value.intValue());
    }
}


                                                                                  THE SYS4U PAPER 2012 |   16
Ⅶ. Method의 이름으로 private Method 실행하기 (2/2)                                    Ⅱ. 실제 사용 예

public class A {
        private int add(int a, int b){ return a+b; }
                                                                      •   실행결과

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

              Class c = Class.forName(“A");

              Class param[] = new Class[2];
              param[0] = Integer.TYPE;
              param[1] = Integer.TYPE;

              Method method = c.getDeclaredMethod("add", param);

              A a = new A();
                                                                                   2
              method.setAccessible(true);
              Object argList[] = new Object[2];
              argList[0] = new Integer(1);
              argList[1] = new Integer(1);
              Object obj = method.invoke(a, argList);
              Integer value = (Integer) obj;

              System.out.println(value.intValue());
          }
    }

                                                                                          THE SYS4U PAPER 2012 |   17
Ⅷ. Field값 변경                                                                    Ⅱ. 실제 사용 예

    public class CF {

            public int i;

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

            Class c = Class.forName(“CF");

            Field field = c.getField("i");

            CF cf = new CF();
            System.out.println ("set 하기 전 : " + cf.i);

             field.setInt(cf, 1);

             System.out.println ("----------------------------------------");
             System.out.println("set 한 후 : " +cf.i);            }
        }
    }

•       실행결과
 set 하기 전 : 0
 ----------------------------------------
 set 한 후 : 1

                                                                                             THE SYS4U PAPER 2012 |   18
Ⅸ. 배열에서의 사용                                                         Ⅱ. 실제 사용 예


    public class CF {

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

            Class c = Class.forName("java.lang.String");

            Object array = Array.newInstance(c, 10);

            Array.set(array, 5, "test");

            String str = (String) Array.get(array, 5);

            System.out.println(str);
        }
    }

•    실행결과


test




                                                                                 THE SYS4U PAPER 2012 |   19
Ⅹ. Reflection을 이용한 Factory pattern                                      Ⅱ. 실제 사용 예


•    Factory Pattern 이란?
    public class PizzaFactoryy {
          public static final String PIZZA="Pizza";
                    유연한 프로그래밍을 위해 instance 생성을 담당하는 Factory Class를 두는 것.
            public Pizza getPizzaInstance(String pizzaType){
                Pizza pizza=null;
                try {
    public class PizzaFactory {
                   String type = new StringBuffer(pizzaType).append(PIZZA).toString();
        public Pizza getPizza(String name){
          Pizza pizza=null; Class.forName(type);
                   Class c =
                   pizza = (Pizza) c.newInstance();
          if(name.equals("cheese")){
                } catch (Exception e) {
              pizza = new CheesePizza();
                   throw new IllegalArgumentException(“No Such Pizza [“+pizzaType+”]”);
                }
          } else if(name.equals("pepperoni")){
                return pizza;
              pizza = new PepperoniPizza();
          }}else if(name.equals("potato")){
              pizza = new PotatoPizza();
          } public static void main(String[] args) {
                PizzaFactoryy f = new PizzaFactoryy();
          return pizza;
        }       Pizza pizza = f.getPizzaInstance("Cheese");
    }           pizza.getPizzaName();
              }
      }
                                                                                          THE SYS4U PAPER 2012 |   20
Ⅲ. 관련 라이브러리




              THE SYS4U PAPER 2012 |   21
Ⅰ. Commons.BeanUtils.cloneBean (1/13)                Ⅲ. 관련 라이브러리




                            cloneBean(Object bean)




            Return                        Object

          Parameters                    복제 할 bean

             설명                         해당 빈 복제




                                                                   THE SYS4U PAPER 2012 |   22
Ⅰ. Commons.BeanUtils.cloneBean 예제 (1/13)           Ⅲ. 관련 라이브러리




    CloneBean bean = new CloneBean();

    CloneBean clone = (CloneBean) BeanUtils.cloneBean(bean);




                                                                 THE SYS4U PAPER 2012 |   23
Ⅰ. Commons.BeanUtils.copyProperties (2/13)               Ⅲ. 관련 라이브러리




                      copyProperties(Object dest, Object orig)




             Return                            void

           Parameters                  원본 bean, 대상 bean,

              설명           원본 대상 빈의 속성과 이름이 모두 같을 경우 속성값 복사




                                                                       THE SYS4U PAPER 2012 |   24
Ⅰ. Commons.BeanUtils.copyProperties 예제 (2/13)        Ⅲ. 관련 라이브러리

 •    멤버 필드

 public int i;
 public String str;



     CopyProperties1 orig = new CopyProperties1();
     orig.setI(1);
     orig.setStr("시스포유");
     System.out.println("orig bean :" + orig);

     CopyProperties1 dest = new CopyProperties1();
     BeanUtils.copyProperties(dest, orig);
     System.out.println("dest bean :" + dest);

 •    실행결과

 orig bean :CopyProperties1 [i=1, str=시스포유]

 dest bean :CopyProperties1 [i=1, str=시스포유]

                                                                   THE SYS4U PAPER 2012 |   25
Ⅰ. Commons.BeanUtils.copyProperties (3/13)           Ⅲ. 관련 라이브러리




            copyProperties(Object bean, String name, Object value)




             Return                          void

           Parameters            원본 bean, 속성 이름, 대상 bean

              설명              원본 빈의 해당 속성값을 대상 빈에 복사




                                                                     THE SYS4U PAPER 2012 |   26
Ⅰ. Commons.BeanUtils.copyProperties 예제 (3/13)          Ⅲ. 관련 라이브러리

 •     멤버 필드

     public int i;
     public String str;




     CopyProperties2 bean = new CopyProperties2();
     System.out.println("copy 하기 전 bean : " + bean);

     BeanUtils.copyProperty(bean, "str", "시스포유");

     System.out.println("copy 한 후 bean : " + bean);



 •    실행결과

 copy 하기 전 bean : CopyProperties2 [i=0, str=null]
 copy 한 후 bean : CopyProperties2 [i=0, str=시스포유]


                                                                     THE SYS4U PAPER 2012 |   27
Ⅰ. Commons.BeanUtils.describe (4/13)                 Ⅲ. 관련 라이브러리




                             describe(Object bean)




             Return                         Map

           Parameters                       bean

              설명            해당 빈의 속성이름과 속성값을 맵으로 리턴




                                                                   THE SYS4U PAPER 2012 |   28
Ⅰ. Commons.BeanUtils.describe 예제 (4/13)                    Ⅲ. 관련 라이브러리

 •     멤버 필드

     public int i;
     public String str;




     Describe bean = new Describe();
     bean.setI(1);
     bean.setStr("시스포유");

     Map<String, String> map = BeanUtils.describe(bean);

     System.out.println(map);


 •    실행결과


 {str=시스포유, class=class commons_beanutils.Describe, i=1}


                                                                         THE SYS4U PAPER 2012 |   29
Ⅰ. Commons.BeanUtils.getArrayProperty (5/13)              Ⅲ. 관련 라이브러리




                  getArrayProperty(Object bean, String name)




             Return                            String[]

           Parameters                Bean, 배열의 속성 이름

              설명                  해당 빈의 배열속성값을 리턴




                                                                        THE SYS4U PAPER 2012 |   30
Ⅰ. Commons.BeanUtils.getArrayProperty 예제 (5/13)                          Ⅲ. 관련 라이브러리

 •    멤버 필드


 public String[] arrayStr = new String[] {"시스포유", "김진아"};




     GetArrayProperty bean = new GetArrayProperty();

     String[] arrayStr = BeanUtils.getArrayProperty(bean, "arrayStr");

     System.out.println("arrayStr[0] : " + arrayStr[0]);
     System.out.println("arrayStr[1] : " + arrayStr[1]);



 •    실행결과
 arrayStr[0] : 시스포유

 arrayStr[1] : 김진아

                                                                                       THE SYS4U PAPER 2012 |   31
Ⅰ. Commons.BeanUtils.getIndexedProperty (6/13)        Ⅲ. 관련 라이브러리




                getIndexedProperty(Object bean, String name)




             Return                          String

          Parameters                  Bean, 배열 속성 이름

              설명                      빈의 배열 요소 리턴




                                                                    THE SYS4U PAPER 2012 |   32
Ⅰ. Commons.BeanUtils.getIndexedProperty 예제 (6/13)                        Ⅲ. 관련 라이브러리


     •     멤버 필드


         public String[] arrayStr = new String[] {"시스포유", "김진아"};




     GetIndexedProperty bean = new GetIndexedProperty();

     String value = BeanUtils.getIndexedProperty(bean, "arrayStr[0]");

     System.out.println("arrayStr[0] : " + value);



 •       실행결과


 arrayStr[0] : 시스포유


                                                                                       THE SYS4U PAPER 2012 |   33
Ⅰ. Commons.BeanUtils.getIndexedProperty (7/13)        Ⅲ. 관련 라이브러리




           getIndexedProperty(Object bean, String name, int index)




             Return                          String

          Parameters              Bean, 배열 속성 이름, 인덱스

              설명            빈의 해당 배열의 지정된 인덱스값을 리턴




                                                                     THE SYS4U PAPER 2012 |   34
Ⅰ. Commons.BeanUtils.getIndexedProperty 예제 (7/13)                     Ⅲ. 관련 라이브러리

 •    멤버 필드


 public String[] arrayStr = new String[] {"시스포유", "김진아"};




     GetIndexedProperty2 bean = new GetIndexedProperty2();

     String value = BeanUtils.getIndexedProperty(bean, "arrayStr" , 1);

     System.out.println("arrayStr[1] : " + value);



 •    실행결과


 arrayStr[1] : 김진아


                                                                                    THE SYS4U PAPER 2012 |   35
Ⅰ. Commons.BeanUtils.getMappedProperty (8/13)        Ⅲ. 관련 라이브러리




               getMappedProperty(Object bean, String name)




            Return                         String

          Parameters                  Bean, 맵 속성이름

             설명             빈의 해당 맵의 지정된 인덱스값을 리턴




                                                                   THE SYS4U PAPER 2012 |   36
Ⅰ. Commons.BeanUtils.getMappedProperty 예제 (8/13)                  Ⅲ. 관련 라이브러리


 •     멤버 필드

 Public Map<String, String> map = new HashMap<String, String>();
  map.put("company", "시스포유");
  map.put("name", "김진아");



     GetMappedProperty1 bean = new GetMappedProperty1();

     String value = BeanUtils.getMappedProperty(bean, "map(company)");

     System.out.println("map(company) : " + value);



 •     실행결과


 map(company) : 시스포유


                                                                                THE SYS4U PAPER 2012 |   37
Ⅰ. Commons.BeanUtils.getMappedProperty (9/13)       Ⅲ. 관련 라이브러리




          getMappedProperty(Object bean, String name, String key)




            Return                         String

          Parameters              Bean, 맵 속성 이름, 인덱스

             설명             빈의 해당 맵의 지정된 인덱스값을 리턴




                                                                    THE SYS4U PAPER 2012 |   38
Ⅰ. Commons.BeanUtils.getMappedProperty 예제 (9/13)                  Ⅲ. 관련 라이브러리

 •     멤버 필드

 Public Map<String, String> map = new HashMap<String, String>();
  map.put("company", "시스포유");
  map.put("name", "김진아");




     GetMappedProperty2 bean = new GetMappedProperty2();

     String value = BeanUtils.getMappedProperty(bean, "map", "name");

     System.out.println("map(name) : " + value);



 •    실행결과


 map(name) : 김진아


                                                                                THE SYS4U PAPER 2012 |   39
Ⅰ. Commons.BeanUtils.getNestedProperty (10/13)        Ⅲ. 관련 라이브러리




                getNestedProperty(Object bean, String name)




            Return                          String

          Parameters                    Bean, 속성 이름

             설명              해당 빈의 중첩된 속성에 접근할 때 사용




                                                                    THE SYS4U PAPER 2012 |   40
Ⅰ. Commons.BeanUtils.getNestedProperty 예제 (10/13)   Ⅲ. 관련 라이브러리




 * 소스 별첨




                                                                  THE SYS4U PAPER 2012 |   41
Ⅰ. Commons.BeanUtils.getProperty (11/13)                  Ⅲ. 관련 라이브러리




                      getProperty(Object bean, String name)




             Return                           String

           Parameters                      Bean , 속성 이름

              설명              해당 빈의 속성이름에 해당하는 값 리턴




                                                                        THE SYS4U PAPER 2012 |   42
Ⅰ. Commons.BeanUtils.getProperty 예제 (11/13)             Ⅲ. 관련 라이브러리


 •     멤버 필드


 int i = 1;




     GetProperty bean = new GetProperty();

     String value = BeanUtils.getProperty(bean, "i");

     System.out.println("GetProperty.i : " + value);


 •     실행결과


 GetProperty.i : 1


                                                                      THE SYS4U PAPER 2012 |   43
Ⅰ. Commons.BeanUtils.populate (12/13)                  Ⅲ. 관련 라이브러리




                      populate(Object bean, Map properties)




             Return                          void

          Parameters                    Bean, 속성 map

              설명          맵의 지정된 이름에 따라 해당 빈의 속성을 채움




                                                                     THE SYS4U PAPER 2012 |   44
Ⅰ. Commons.BeanUtils.populate 예제 (12/13)                          Ⅲ. 관련 라이브러리

     •   멤버 필드

     public String company;
     public String name;



     Map<String, String> properties = new HashMap<String, String>();
     properties.put("company", "시스포유");
     properties.put("name", "김진아");

     Populate bean = new Populate();
     System.out.println("populate 하기 전 bean : " + bean);

     BeanUtils.populate(bean, properties);
     System.out.println("populate 한 후 bean : " + bean);

 •       실행결과

 populate 하기 전 bean : Populate [company=null, name=null ]
 populate 한 후 bean : Populate [company=시스포유, name=김진아]

                                                                                THE SYS4U PAPER 2012 |   45
Ⅰ. Commons.BeanUtils.setProperty (13/13)             Ⅲ. 관련 라이브러리




             setProperty(Object bean, String name, Object value)




             Return                        void

           Parameters            Bean, 속성 이름, 속성이름의 값

              설명                  해당 빈의 속성값에 값을 설정




                                                                   THE SYS4U PAPER 2012 |   46
Ⅰ. Commons.BeanUtils.setProperty 예제 (13/13)           Ⅲ. 관련 라이브러리

 •     멤버 필드

     public String company;
     public String name;




     SetProperty bean = new SetProperty();
     System.out.println("set 하기 전 bean : "+ bean);

     BeanUtils.setProperty(bean, "name", "김진아");

     System.out.println("set 한 후   bean : "+ bean);



 •    실행결과

 set 하기 전 bean : SetProperty [company=null, name=null ]
 set 한 후 bean : SetProperty [company=null, name=김진아]


                                                                    THE SYS4U PAPER 2012 |   47
Ⅳ. Q&A




         THE SYS4U PAPER 2012 |   48
감사합니다.




         THE SYS4U PAPER 2012 |   49

More Related Content

PPTX
Java Annotation과 MyBatis로 나만의 ORM Framework을 만들어보자
PPT
I phone 2 release
PPTX
파이썬 class 및 인스턴스 생성 이해하기
PPT
Ai C#세미나
PPTX
python data model 이해하기
PPTX
파이썬+클래스+구조+이해하기 20160310
PPTX
파이썬+객체지향+이해하기 20160131
PDF
SpringCamp 2013 : About Jdk8
Java Annotation과 MyBatis로 나만의 ORM Framework을 만들어보자
I phone 2 release
파이썬 class 및 인스턴스 생성 이해하기
Ai C#세미나
python data model 이해하기
파이썬+클래스+구조+이해하기 20160310
파이썬+객체지향+이해하기 20160131
SpringCamp 2013 : About Jdk8

What's hot (20)

PPT
강의자료3
PPTX
빠르게 활용하는 파이썬3 스터디(ch1~4)
PPTX
파이썬+함수이해하기 20160229
PDF
Java 강의자료 ed11
PDF
Java programming pdf
PPTX
강의자료 2
PPTX
파이썬 namespace Binding 이해하기
PPTX
Processing 기초 이해하기_20160713
PPTX
파이썬 객체 클래스 이해하기
PDF
Python Programming: Class and Object Oriented Programming
PPT
강의자료4
PPTX
파이썬 Descriptor이해하기 20160403
PPTX
파이썬 함수 이해하기
PDF
Protocol Oriented Programming in Swift
PDF
안드로이드 세미나
PPTX
파이썬+함수 데코레이터+이해하기 20160229
PDF
[Main Session] 미래의 Java 미리보기 - 앰버와 발할라 프로젝트를 중심으로
PPTX
파이썬+Operator+이해하기 20160409
PDF
나에 첫번째 자바8 람다식 지앤선
PDF
자바8 람다 나머지 공개
강의자료3
빠르게 활용하는 파이썬3 스터디(ch1~4)
파이썬+함수이해하기 20160229
Java 강의자료 ed11
Java programming pdf
강의자료 2
파이썬 namespace Binding 이해하기
Processing 기초 이해하기_20160713
파이썬 객체 클래스 이해하기
Python Programming: Class and Object Oriented Programming
강의자료4
파이썬 Descriptor이해하기 20160403
파이썬 함수 이해하기
Protocol Oriented Programming in Swift
안드로이드 세미나
파이썬+함수 데코레이터+이해하기 20160229
[Main Session] 미래의 Java 미리보기 - 앰버와 발할라 프로젝트를 중심으로
파이썬+Operator+이해하기 20160409
나에 첫번째 자바8 람다식 지앤선
자바8 람다 나머지 공개
Ad

Viewers also liked (20)

PDF
About Color_SYS4U
PDF
iOS Human Interface Guidlines #14_SYS4U
PDF
NAT and Hole Punching_SYS4U I&C
PDF
JavaEE6 Tutorial - Java Message Service_sys4u
PDF
Java_Concurrency_Programming_SYS4U
PDF
2013 UX Design Trend Report Part 3_SYS4U I&C
PDF
Aspect Oriented Programming_SYS4U I&C
PDF
2012 UX Design Trend Report Part 2_SYS4U I&C
PDF
iOS Human Interface Guidlines #15_SYS4U
PDF
Web Accessibility_SYS4U
PDF
UIX UNIT_Several UI Teminologies Easy To Miss_SYS4U I&C
PDF
Html5_SYS4U
PDF
웹어워드컨퍼런스강연자료 시스포유
PDF
2012 UX Design Trend Report Part 1_SYS4U I&C
PDF
UX Planning Training Course_SYS4U I&C
PDF
UX Layout Design_SYS4U
PDF
Memory_leak_patterns_in_JavaScript_SYS4U
PDF
Observer Design Pattern in Java_SYS4U
PDF
iOS Human Interface Guidlines #11_SYS4U
PDF
iOS Human Interface Guidlines #12_SYS4U
About Color_SYS4U
iOS Human Interface Guidlines #14_SYS4U
NAT and Hole Punching_SYS4U I&C
JavaEE6 Tutorial - Java Message Service_sys4u
Java_Concurrency_Programming_SYS4U
2013 UX Design Trend Report Part 3_SYS4U I&C
Aspect Oriented Programming_SYS4U I&C
2012 UX Design Trend Report Part 2_SYS4U I&C
iOS Human Interface Guidlines #15_SYS4U
Web Accessibility_SYS4U
UIX UNIT_Several UI Teminologies Easy To Miss_SYS4U I&C
Html5_SYS4U
웹어워드컨퍼런스강연자료 시스포유
2012 UX Design Trend Report Part 1_SYS4U I&C
UX Planning Training Course_SYS4U I&C
UX Layout Design_SYS4U
Memory_leak_patterns_in_JavaScript_SYS4U
Observer Design Pattern in Java_SYS4U
iOS Human Interface Guidlines #11_SYS4U
iOS Human Interface Guidlines #12_SYS4U
Ad

Similar to Java reflection & introspection_SYS4U I&C (20)

PDF
테스트 가능한 소프트웨어 설계와 TDD작성 패턴 (Testable design and TDD)
PPTX
Design patterns
 
PPT
자바스터디(6기) 4
PPTX
Java Virtual Machine, Call stack, Java Byte Code
PPTX
The roadtocodecraft
PDF
HolubOnPatterns/chapter2_2
PDF
Swift3 subscript inheritance initialization
PDF
Api design for c++ 6장
PDF
08장 객체와 클래스 (기본)
PPTX
Java mentoring of samsung scsc 2
PDF
(스프링교육/마이바티스교육학원추천_탑크리에듀)#10.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)
PDF
Java in 2 hours
KEY
Java start01 in 2hours
PPTX
Clean code
PDF
20201121 코드 삼분지계
PDF
5장 객체와클래스
PDF
실용주의 디자인패턴 2 인터페이스로 프로그래밍하기
PDF
2014.07.26 KSUG와 지앤선이 함께하는 테크니컬 세미나 - 자바8 람다 나머지 이야기 (박성철)
PPTX
Tech-days 미니 토요세미나 - 3회 C#편 PPT 자료
PPTX
파이썬 스터디 15장
테스트 가능한 소프트웨어 설계와 TDD작성 패턴 (Testable design and TDD)
Design patterns
 
자바스터디(6기) 4
Java Virtual Machine, Call stack, Java Byte Code
The roadtocodecraft
HolubOnPatterns/chapter2_2
Swift3 subscript inheritance initialization
Api design for c++ 6장
08장 객체와 클래스 (기본)
Java mentoring of samsung scsc 2
(스프링교육/마이바티스교육학원추천_탑크리에듀)#10.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)
Java in 2 hours
Java start01 in 2hours
Clean code
20201121 코드 삼분지계
5장 객체와클래스
실용주의 디자인패턴 2 인터페이스로 프로그래밍하기
2014.07.26 KSUG와 지앤선이 함께하는 테크니컬 세미나 - 자바8 람다 나머지 이야기 (박성철)
Tech-days 미니 토요세미나 - 3회 C#편 PPT 자료
파이썬 스터디 15장

More from sys4u (17)

PDF
iOS Human Interface Guidlines #13_SYS4U
PDF
iOS Human Interface Guidlines #10_SYS4U
PDF
iOS Human Interface Guidlines #8_SYS4U
PDF
iOS Human Interface Guidlines #7_SYS4U
PDF
iOS Human Interface Guidlines #5_SYS4U
PDF
iOS_Human_Interface_Guidlines_#4_SYS4U
PDF
30_eCommerce_sites_using_html5_SYS4U
PDF
iOS Human Interface Guidlines #3_SYS4U
PDF
Advanced SWOT Analysis of e-commerce_SYS4U
PDF
Proxy_design_pattern_in_Java_SYS4U
PDF
Implementing_AOP_in_Spring_SYS4U
PDF
iOS Human_Interface_Guidlines_#2_SYS4U
PDF
iOS Human_Interface_Guidlines_#1_SYS4U
PDF
Promotions_2nd_SYS4U I&C
PDF
JavaScript Profiling With The Chrome Developer Tools_SYS4U I&C
PDF
From Java code to Java heap_SYS4U I&C
PDF
Introduction to Fork Join Framework_SYS4U I&C
iOS Human Interface Guidlines #13_SYS4U
iOS Human Interface Guidlines #10_SYS4U
iOS Human Interface Guidlines #8_SYS4U
iOS Human Interface Guidlines #7_SYS4U
iOS Human Interface Guidlines #5_SYS4U
iOS_Human_Interface_Guidlines_#4_SYS4U
30_eCommerce_sites_using_html5_SYS4U
iOS Human Interface Guidlines #3_SYS4U
Advanced SWOT Analysis of e-commerce_SYS4U
Proxy_design_pattern_in_Java_SYS4U
Implementing_AOP_in_Spring_SYS4U
iOS Human_Interface_Guidlines_#2_SYS4U
iOS Human_Interface_Guidlines_#1_SYS4U
Promotions_2nd_SYS4U I&C
JavaScript Profiling With The Chrome Developer Tools_SYS4U I&C
From Java code to Java heap_SYS4U I&C
Introduction to Fork Join Framework_SYS4U I&C

Java reflection & introspection_SYS4U I&C

  • 1. THE SYS4U DODUMENT Java Reflection & Introspection 2012.08.21 김진아 사원 © 2012 SYS4U I&C All rights reserved.
  • 2. 목차 I. 개념 Ⅲ. 관련 라이브러리 1. Reflection 이란? 2. Introspection 이란? 1. Commons.BeanUtils 3. Reflection 과 Introspection 의 차이점 Ⅳ. Q&A II. 실제 사용 예 1. Instance의 생성 2. Class Type 생성 3. Instanceof 대체 Reflection API 4. Class의생성자의 정보 얻기 5. Class의 Field 얻기 6. Class의 Method 얻기 7. Method의 이름으로 Method 실행하기 8. Field값 변경 9. 배열에서의 사용 10. Reflection을 이용한 Factory pattern THE SYS4U PAPER 2012 | 2
  • 3. I. 개념 THE SYS4U PAPER 2012 | 3
  • 4. I. Reflection 이란? Ⅰ. 개념 Java.lang.reflect 패키지 사용 클래스 인스턴스로부터 그 인스턴스가 표현하는 멤버, 필드, 메소드에 접근할 수 있는 기능 클래스 구조에 대한 정보 뿐만 아니라 객체의 생성, 메소드 호출, 필드 접근까지 가능 THE SYS4U PAPER 2012 | 4
  • 5. Ⅱ. Introspection 이란? Ⅰ. 개념 빈의 프로퍼티와 메소드 등을 알려주기 위해 빈의 디자인 패턴을 자동으로 분석하는 과정 객체의 클래스, 구현 메소드, 필드 등의 객체정보를 조사하는 과정을 의미 THE SYS4U PAPER 2012 | 5
  • 6. Ⅲ. Reflection 과 Introspection의 차이점 Ⅰ. 개념 Reflection 조작 Introspection 조사 THE SYS4U PAPER 2012 | 6
  • 7. Ⅱ. 실제 사용 예 THE SYS4U PAPER 2012 | 7
  • 8. Ⅰ. Instance의 생성 (1/3) Ⅱ. 실제 사용 예 • new public class Sample { private void outputMessage(){ System.out.println("outputMessage"); } public static void main(String[] args) throws Exception { Sample sample1 = new Sample(); sample1.outputMessage(); } } • 실행결과 outputMessage THE SYS4U PAPER 2012 | 8
  • 9. Ⅰ. Instance의 생성 (2/3) Ⅱ. 실제 사용 예 • clone public class Sample implements Cloneable{ private void outputMessage(){ System.out.println("outputMessage"); } public static void main(String[] args) throws Exception { Sample sample1 = new Sample(); Sample sample3 = (Sample) sample1.clone(); sample3.outputMessage(); } } • 실행결과 outputMessage THE SYS4U PAPER 2012 | 9
  • 10. Ⅰ. Instance의 생성 (3/3) Ⅱ. 실제 사용 예 • Class<T>.newInstance public class Sample { private void outputMessage(){ System.out.println("outputMessage"); } public static void main(String[] args) throws Exception { Class c = Class.forName("Sample"); Sample sample2 = c.newInstance(); sample2.outputMessage(); } } • 실행결과 outputMessage THE SYS4U PAPER 2012 | 10
  • 11. Ⅱ. Class Type 생성 Ⅱ. 실제 사용 예 public static void main(String[] args) { Class c1 = Class.forName("java.lang.String"); } public static void main(String[] args) { Class<Integer> c2 = int.class; } public static void main(String[] args) { Class<Integer> c3 = Integer.TYPE; } THE SYS4U PAPER 2012 | 11
  • 12. Ⅲ. Instanceof 대체 Reflection API Ⅱ. 실제 사용 예 public class A { public static void main(String[] args) throws Exception { Class c = Class.forName("A"); boolean b1 = c.isInstance(new Integer(65)); System.out.println("new Integer(65) == > "+b1); boolean b2 = c.isInstance(new A()); System.out.println("new A() == > "+b2); } } • 실행결과 new Integer(65) == > false new A() == > true THE SYS4U PAPER 2012 | 12
  • 13. Ⅳ. Class의 생성자의 정보 얻기 Ⅱ. 실제 사용 예 public class Const { public Const(int i, String str){ } • 실행결과 public static void main(String[] args) throws Exception{ Class c= Class.forName("Const"); Constructor constList[] = c.getDeclaredConstructors(); Class Name : class Const Constructor Name : i < constList.length; i++) { for (int i = 0; Const ------------------------------------------------ Constructor constructor = constList[i]; param 0 :System.out.println("Class Name int : " + constructor.getDeclaringClass()); class out.println("Constructor Name : "+ constructor.getName()); param 1 :System.java.lang.String System.out.println("------------------------------------------------"); Class param[] = constructor.getParameterTypes(); for (int j = 0; j < param.length; j++) { System.out.println("param "+ j +" : “ + param[ j]); } } } } THE SYS4U PAPER 2012 | 13
  • 14. Ⅴ. Class Field 얻기 Ⅱ. 실제 사용 예 public class F { private int a; public static final String b="b"; double c; Class : class F Field Name : a void main(String[] args) throws Exception { public static Field Type : int Field Modifiers : private Class cls = Class.forName(“F"); ------------------------------------------------- Class : Field fieldList[] = c.getDeclaredFields(); class F Field Name : b Field Type (int i =java.lang.String for : class 0; i < fieldList.length; i++) { Field Modifiers : public static final Field field = fieldList[i]; ------------------------------------------------- Class : class F out.println("Class : " + field.getDeclaringClass()); System. Field Name : c out.println("Field Name : " + field.getName()); System. System.out. Field Type : double println("Field Type : " + field.getType()); Field Modifiers : out.println("Field Modifiers : " + Modifier.toString(field.getModifiers())); System. System.out.println("-------------------------------------------------"); ------------------------------------------------- } } } THE SYS4U PAPER 2012 | 14
  • 15. Ⅵ. Class의 Method 얻기 Ⅱ. 실제 사용 예 public class M { private int test(String str,int i) throws NullPointerException{ if(str ==null || str.equals("")) { throw new NullPointerException(); } return -1; } public static void main(String[] args) throws Exception { Class cls : Class.forName(“M"); Class Name = class M Method Name : main = c.getDeclaredMethods(); Method methodList[] Param 0 : class [Ljava.lang.String; for (int i = 0; i < methodList.length; i++) { exc 0 : class java.lang.Exception Method method = methodList[i]; ReturnType : void System.out.println("Class Name : " + method.getDeclaringClass()); ------------------------------------------------method.getName()); System.out.println("Method Name : "+ Class Name : class M Method Name : test = method.getParameterTypes(); Class paramList[] Param 0 for (int java.lang.String : class j = 0; j < paramList.length; j++) { Param 1 : int System.out.println("Param " + j + " : " + paramList[ j]); } exc 0 : class java.lang.NullPointerException ReturnType excList[]= method.getExceptionTypes(); Class : int ------------------------------------------------ { for (int j = 0; j < excList.length; j++) System.out.println("exc " + j + " : " + excList[ j]); } System.out.println("ReturnType : " + method.getReturnType()); System.out.println("------------------------------------------------"); } } THE SYS4U PAPER 2012 | 15
  • 16. Ⅶ. Method의 이름으로 Method 실행하기 (1/2) Ⅱ. 실제 사용 예 public class A { public int add(int a, int b) { return a+b; } • 실행결과 } public class B { public static void main(String[] args) throws Exception { Class c = Class.forName(“A"); Class param[] = new Class[2]; param[0] = Integer.TYPE; param[1] = Integer.TYPE; Method method = c.getDeclaredMethod("add", param); 2 A a = new A(); Object argList[] = new Object[2]; argList[0] = new Integer(1); argList[1] = new Integer(1); Object obj = method.invoke(a, argList); Integer value = (Integer) obj; System.out.println(value.intValue()); } } THE SYS4U PAPER 2012 | 16
  • 17. Ⅶ. Method의 이름으로 private Method 실행하기 (2/2) Ⅱ. 실제 사용 예 public class A { private int add(int a, int b){ return a+b; } • 실행결과 } public class B { public static void main(String[] args) throws Exception { Class c = Class.forName(“A"); Class param[] = new Class[2]; param[0] = Integer.TYPE; param[1] = Integer.TYPE; Method method = c.getDeclaredMethod("add", param); A a = new A(); 2 method.setAccessible(true); Object argList[] = new Object[2]; argList[0] = new Integer(1); argList[1] = new Integer(1); Object obj = method.invoke(a, argList); Integer value = (Integer) obj; System.out.println(value.intValue()); } } THE SYS4U PAPER 2012 | 17
  • 18. Ⅷ. Field값 변경 Ⅱ. 실제 사용 예 public class CF { public int i; public static void main(String[] args) throws Exception { Class c = Class.forName(“CF"); Field field = c.getField("i"); CF cf = new CF(); System.out.println ("set 하기 전 : " + cf.i); field.setInt(cf, 1); System.out.println ("----------------------------------------"); System.out.println("set 한 후 : " +cf.i); } } } • 실행결과 set 하기 전 : 0 ---------------------------------------- set 한 후 : 1 THE SYS4U PAPER 2012 | 18
  • 19. Ⅸ. 배열에서의 사용 Ⅱ. 실제 사용 예 public class CF { public static void main(String[] args) throws Exception { Class c = Class.forName("java.lang.String"); Object array = Array.newInstance(c, 10); Array.set(array, 5, "test"); String str = (String) Array.get(array, 5); System.out.println(str); } } • 실행결과 test THE SYS4U PAPER 2012 | 19
  • 20. Ⅹ. Reflection을 이용한 Factory pattern Ⅱ. 실제 사용 예 • Factory Pattern 이란? public class PizzaFactoryy { public static final String PIZZA="Pizza"; 유연한 프로그래밍을 위해 instance 생성을 담당하는 Factory Class를 두는 것. public Pizza getPizzaInstance(String pizzaType){ Pizza pizza=null; try { public class PizzaFactory { String type = new StringBuffer(pizzaType).append(PIZZA).toString(); public Pizza getPizza(String name){ Pizza pizza=null; Class.forName(type); Class c = pizza = (Pizza) c.newInstance(); if(name.equals("cheese")){ } catch (Exception e) { pizza = new CheesePizza(); throw new IllegalArgumentException(“No Such Pizza [“+pizzaType+”]”); } } else if(name.equals("pepperoni")){ return pizza; pizza = new PepperoniPizza(); }}else if(name.equals("potato")){ pizza = new PotatoPizza(); } public static void main(String[] args) { PizzaFactoryy f = new PizzaFactoryy(); return pizza; } Pizza pizza = f.getPizzaInstance("Cheese"); } pizza.getPizzaName(); } } THE SYS4U PAPER 2012 | 20
  • 21. Ⅲ. 관련 라이브러리 THE SYS4U PAPER 2012 | 21
  • 22. Ⅰ. Commons.BeanUtils.cloneBean (1/13) Ⅲ. 관련 라이브러리 cloneBean(Object bean) Return Object Parameters 복제 할 bean 설명 해당 빈 복제 THE SYS4U PAPER 2012 | 22
  • 23. Ⅰ. Commons.BeanUtils.cloneBean 예제 (1/13) Ⅲ. 관련 라이브러리 CloneBean bean = new CloneBean(); CloneBean clone = (CloneBean) BeanUtils.cloneBean(bean); THE SYS4U PAPER 2012 | 23
  • 24. Ⅰ. Commons.BeanUtils.copyProperties (2/13) Ⅲ. 관련 라이브러리 copyProperties(Object dest, Object orig) Return void Parameters 원본 bean, 대상 bean, 설명 원본 대상 빈의 속성과 이름이 모두 같을 경우 속성값 복사 THE SYS4U PAPER 2012 | 24
  • 25. Ⅰ. Commons.BeanUtils.copyProperties 예제 (2/13) Ⅲ. 관련 라이브러리 • 멤버 필드 public int i; public String str; CopyProperties1 orig = new CopyProperties1(); orig.setI(1); orig.setStr("시스포유"); System.out.println("orig bean :" + orig); CopyProperties1 dest = new CopyProperties1(); BeanUtils.copyProperties(dest, orig); System.out.println("dest bean :" + dest); • 실행결과 orig bean :CopyProperties1 [i=1, str=시스포유] dest bean :CopyProperties1 [i=1, str=시스포유] THE SYS4U PAPER 2012 | 25
  • 26. Ⅰ. Commons.BeanUtils.copyProperties (3/13) Ⅲ. 관련 라이브러리 copyProperties(Object bean, String name, Object value) Return void Parameters 원본 bean, 속성 이름, 대상 bean 설명 원본 빈의 해당 속성값을 대상 빈에 복사 THE SYS4U PAPER 2012 | 26
  • 27. Ⅰ. Commons.BeanUtils.copyProperties 예제 (3/13) Ⅲ. 관련 라이브러리 • 멤버 필드 public int i; public String str; CopyProperties2 bean = new CopyProperties2(); System.out.println("copy 하기 전 bean : " + bean); BeanUtils.copyProperty(bean, "str", "시스포유"); System.out.println("copy 한 후 bean : " + bean); • 실행결과 copy 하기 전 bean : CopyProperties2 [i=0, str=null] copy 한 후 bean : CopyProperties2 [i=0, str=시스포유] THE SYS4U PAPER 2012 | 27
  • 28. Ⅰ. Commons.BeanUtils.describe (4/13) Ⅲ. 관련 라이브러리 describe(Object bean) Return Map Parameters bean 설명 해당 빈의 속성이름과 속성값을 맵으로 리턴 THE SYS4U PAPER 2012 | 28
  • 29. Ⅰ. Commons.BeanUtils.describe 예제 (4/13) Ⅲ. 관련 라이브러리 • 멤버 필드 public int i; public String str; Describe bean = new Describe(); bean.setI(1); bean.setStr("시스포유"); Map<String, String> map = BeanUtils.describe(bean); System.out.println(map); • 실행결과 {str=시스포유, class=class commons_beanutils.Describe, i=1} THE SYS4U PAPER 2012 | 29
  • 30. Ⅰ. Commons.BeanUtils.getArrayProperty (5/13) Ⅲ. 관련 라이브러리 getArrayProperty(Object bean, String name) Return String[] Parameters Bean, 배열의 속성 이름 설명 해당 빈의 배열속성값을 리턴 THE SYS4U PAPER 2012 | 30
  • 31. Ⅰ. Commons.BeanUtils.getArrayProperty 예제 (5/13) Ⅲ. 관련 라이브러리 • 멤버 필드 public String[] arrayStr = new String[] {"시스포유", "김진아"}; GetArrayProperty bean = new GetArrayProperty(); String[] arrayStr = BeanUtils.getArrayProperty(bean, "arrayStr"); System.out.println("arrayStr[0] : " + arrayStr[0]); System.out.println("arrayStr[1] : " + arrayStr[1]); • 실행결과 arrayStr[0] : 시스포유 arrayStr[1] : 김진아 THE SYS4U PAPER 2012 | 31
  • 32. Ⅰ. Commons.BeanUtils.getIndexedProperty (6/13) Ⅲ. 관련 라이브러리 getIndexedProperty(Object bean, String name) Return String Parameters Bean, 배열 속성 이름 설명 빈의 배열 요소 리턴 THE SYS4U PAPER 2012 | 32
  • 33. Ⅰ. Commons.BeanUtils.getIndexedProperty 예제 (6/13) Ⅲ. 관련 라이브러리 • 멤버 필드 public String[] arrayStr = new String[] {"시스포유", "김진아"}; GetIndexedProperty bean = new GetIndexedProperty(); String value = BeanUtils.getIndexedProperty(bean, "arrayStr[0]"); System.out.println("arrayStr[0] : " + value); • 실행결과 arrayStr[0] : 시스포유 THE SYS4U PAPER 2012 | 33
  • 34. Ⅰ. Commons.BeanUtils.getIndexedProperty (7/13) Ⅲ. 관련 라이브러리 getIndexedProperty(Object bean, String name, int index) Return String Parameters Bean, 배열 속성 이름, 인덱스 설명 빈의 해당 배열의 지정된 인덱스값을 리턴 THE SYS4U PAPER 2012 | 34
  • 35. Ⅰ. Commons.BeanUtils.getIndexedProperty 예제 (7/13) Ⅲ. 관련 라이브러리 • 멤버 필드 public String[] arrayStr = new String[] {"시스포유", "김진아"}; GetIndexedProperty2 bean = new GetIndexedProperty2(); String value = BeanUtils.getIndexedProperty(bean, "arrayStr" , 1); System.out.println("arrayStr[1] : " + value); • 실행결과 arrayStr[1] : 김진아 THE SYS4U PAPER 2012 | 35
  • 36. Ⅰ. Commons.BeanUtils.getMappedProperty (8/13) Ⅲ. 관련 라이브러리 getMappedProperty(Object bean, String name) Return String Parameters Bean, 맵 속성이름 설명 빈의 해당 맵의 지정된 인덱스값을 리턴 THE SYS4U PAPER 2012 | 36
  • 37. Ⅰ. Commons.BeanUtils.getMappedProperty 예제 (8/13) Ⅲ. 관련 라이브러리 • 멤버 필드 Public Map<String, String> map = new HashMap<String, String>(); map.put("company", "시스포유"); map.put("name", "김진아"); GetMappedProperty1 bean = new GetMappedProperty1(); String value = BeanUtils.getMappedProperty(bean, "map(company)"); System.out.println("map(company) : " + value); • 실행결과 map(company) : 시스포유 THE SYS4U PAPER 2012 | 37
  • 38. Ⅰ. Commons.BeanUtils.getMappedProperty (9/13) Ⅲ. 관련 라이브러리 getMappedProperty(Object bean, String name, String key) Return String Parameters Bean, 맵 속성 이름, 인덱스 설명 빈의 해당 맵의 지정된 인덱스값을 리턴 THE SYS4U PAPER 2012 | 38
  • 39. Ⅰ. Commons.BeanUtils.getMappedProperty 예제 (9/13) Ⅲ. 관련 라이브러리 • 멤버 필드 Public Map<String, String> map = new HashMap<String, String>(); map.put("company", "시스포유"); map.put("name", "김진아"); GetMappedProperty2 bean = new GetMappedProperty2(); String value = BeanUtils.getMappedProperty(bean, "map", "name"); System.out.println("map(name) : " + value); • 실행결과 map(name) : 김진아 THE SYS4U PAPER 2012 | 39
  • 40. Ⅰ. Commons.BeanUtils.getNestedProperty (10/13) Ⅲ. 관련 라이브러리 getNestedProperty(Object bean, String name) Return String Parameters Bean, 속성 이름 설명 해당 빈의 중첩된 속성에 접근할 때 사용 THE SYS4U PAPER 2012 | 40
  • 41. Ⅰ. Commons.BeanUtils.getNestedProperty 예제 (10/13) Ⅲ. 관련 라이브러리 * 소스 별첨 THE SYS4U PAPER 2012 | 41
  • 42. Ⅰ. Commons.BeanUtils.getProperty (11/13) Ⅲ. 관련 라이브러리 getProperty(Object bean, String name) Return String Parameters Bean , 속성 이름 설명 해당 빈의 속성이름에 해당하는 값 리턴 THE SYS4U PAPER 2012 | 42
  • 43. Ⅰ. Commons.BeanUtils.getProperty 예제 (11/13) Ⅲ. 관련 라이브러리 • 멤버 필드 int i = 1; GetProperty bean = new GetProperty(); String value = BeanUtils.getProperty(bean, "i"); System.out.println("GetProperty.i : " + value); • 실행결과 GetProperty.i : 1 THE SYS4U PAPER 2012 | 43
  • 44. Ⅰ. Commons.BeanUtils.populate (12/13) Ⅲ. 관련 라이브러리 populate(Object bean, Map properties) Return void Parameters Bean, 속성 map 설명 맵의 지정된 이름에 따라 해당 빈의 속성을 채움 THE SYS4U PAPER 2012 | 44
  • 45. Ⅰ. Commons.BeanUtils.populate 예제 (12/13) Ⅲ. 관련 라이브러리 • 멤버 필드 public String company; public String name; Map<String, String> properties = new HashMap<String, String>(); properties.put("company", "시스포유"); properties.put("name", "김진아"); Populate bean = new Populate(); System.out.println("populate 하기 전 bean : " + bean); BeanUtils.populate(bean, properties); System.out.println("populate 한 후 bean : " + bean); • 실행결과 populate 하기 전 bean : Populate [company=null, name=null ] populate 한 후 bean : Populate [company=시스포유, name=김진아] THE SYS4U PAPER 2012 | 45
  • 46. Ⅰ. Commons.BeanUtils.setProperty (13/13) Ⅲ. 관련 라이브러리 setProperty(Object bean, String name, Object value) Return void Parameters Bean, 속성 이름, 속성이름의 값 설명 해당 빈의 속성값에 값을 설정 THE SYS4U PAPER 2012 | 46
  • 47. Ⅰ. Commons.BeanUtils.setProperty 예제 (13/13) Ⅲ. 관련 라이브러리 • 멤버 필드 public String company; public String name; SetProperty bean = new SetProperty(); System.out.println("set 하기 전 bean : "+ bean); BeanUtils.setProperty(bean, "name", "김진아"); System.out.println("set 한 후 bean : "+ bean); • 실행결과 set 하기 전 bean : SetProperty [company=null, name=null ] set 한 후 bean : SetProperty [company=null, name=김진아] THE SYS4U PAPER 2012 | 47
  • 48. Ⅳ. Q&A THE SYS4U PAPER 2012 | 48
  • 49. 감사합니다. THE SYS4U PAPER 2012 | 49