공부/소소한 개발

JAVA Reflection

무는빼주세요 2022. 5. 15. 00:24

Java Reflection : 클래스의 타입, 메소드, 변수 등에 대해 정보가 없는 상태에서도 접근 할 수 있는 API 

 

예: 특정 클래스의 메소드에 대해 알고 싶은 경우

import java.lang.reflect.*;

   public class method1 {
      private int f1(
       Object p, int x) throws NullPointerException
      {
         if (p == null)
            throw new NullPointerException();
         return x;
      }
        
      public static void main(String args[])
      {
         try {
           Class cls = Class.forName("method1");
        
            Method methlist[] 
              = cls.getDeclaredMethods();
            for (int i = 0; i < methlist.length;
               i++) {  
               Method m = methlist[i];
               System.out.println("name 
                 = " + m.getName());
               System.out.println("decl class = " +
                              m.getDeclaringClass());
               Class pvec[] = m.getParameterTypes();
               for (int j = 0; j < pvec.length; j++)
                  System.out.println("
                   param #" + j + " " + pvec[j]);
               Class evec[] = m.getExceptionTypes();
               for (int j = 0; j < evec.length; j++)
                  System.out.println("exc #" + j 
                    + " " + evec[j]);
               System.out.println("return type = " +
                                  m.getReturnType());
               System.out.println("-----");
            }
         }
         catch (Throwable e) {
            System.err.println(e);
         }
      }
   }

 

결과값 :

name = f1
   decl class = class method1
   param #0 class java.lang.Object
   param #1 int
   exc #0 class java.lang.NullPointerException
   return type = int
   -----
   name = main
   decl class = class method1
   param #0 class [Ljava.lang.String;
   return type = void
   -----

 

사용 : 런타임 중 동적 사용, 프레임워크 개발, IDE의 자동 완성 등

 

 

참조 :

https://www.oracle.com/technical-resources/articles/java/javareflection.html

https://tecoble.techcourse.co.kr/post/2020-07-16-reflection-api/