예제를 위한 클래스

1. ExampleSuperClass : 부모클래스

1
2
3
4
5
package Java.reflection;
 
public class ExampleSuperClass {
}
 
cs

 

2. ExampleClass : 예제 클래스

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
package Java.reflection;
 
public class ExampleClass extends ExampleSuperClass {
   
   private static final String CONSTANT_FIELD = "constant_field";
   public int i = 1;
   public String publicField = "publicStrField";
   private String privateField = "privateStrField";
   
   public ExampleClass() { 
   }
   
   public ExampleClass(Object a) throws NullPointerException {
   }
   
   private int privateMethod(Object a, int b) throws NullPointerException {
      if(a == null) {
         throw new NullPointerException();
      }
      return b;
   }
   
   public String addStrInt(String a, int b) {
      return a+b;
   }
}
cs

 

3. ExampleChildClass : 자식 클래스

1
2
3
4
package Java.reflection;
 
public class ExampleChildClass extends ExampleClass {       
}
cs

 

 

Java Reflection 의 사용 예

1. isInstance 사용법 

instanceof 와 같은 역할을 수행

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package Java.reflection;
 
//https://gyrfalcon.tistory.com/entry/Java-Reflection
 
//instance of
public class Reflection1_instanceof {
   public static void main(String[] args) {
      
      //classA.isInstance(B);
      //B가 A의 인스턴스인지를 확인
      Class clazz = ExampleClass.class;
      
      boolean rs1 = clazz.isInstance(new ExampleSuperClass());
      System.out.println(rs1);
      boolean rs2 = clazz.isInstance(new ExampleClass());
      System.out.println(rs2);
      boolean rs3 = clazz.isInstance(new ExampleChildClass());
      System.out.println(rs3);
 
   }
}
 
cs

[결과]

false
true
true

 

2. 클래스에서 메소드 정보 가져오기

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package Java.reflection;
 
import java.lang.reflect.Method;
 
//Method 정보 가져오기
public class Reflection2_FindMethod {
 
   public static void main(String[] args) throws Exception {
      
      //1. class 가져오기
      Class clazz = Class.forName("Java.reflection.ExampleClass");
      //1-1. class 가져오기(위와 같다)
      Class clazz1 = ExampleClass.class;
      
      //2. class 에서 method 가져오기
      Method methodArr[] = clazz.getDeclaredMethods();
      
      for(Method method : methodArr) {
         
         //1) 메소드명 가져오기
         System.out.println("name = " + method.getName());
         
         //2) 선언된 클래스명 가져오기
         System.out.println("class = " + method.getDeclaringClass());
         
         //3) Parameter Type 가져오기
         Class paramTypes[] = method.getParameterTypes();
         for(Class p : paramTypes) {
            System.out.println("param type : " + p);
         }
      
         //4) exception Type 가져오기
         Class exceptionTypes[] = method.getExceptionTypes();
         for(Class e : exceptionTypes) {
            System.out.println("exception type : " + e);
         }
         
         //5) return Type 가져오기
         System.out.println("return type : "+method.getReturnType());
         
         System.out.println();
      }
   }
}
 
cs

[결과]

name = privateMethod
class = class Java.reflection.ExampleClass
param type : class java.lang.Object
param type : int
exception type : class java.lang.NullPointerException
return type : int

name = addStrInt
class = class Java.reflection.ExampleClass
param type : class java.lang.String
param type : int
return type : class java.lang.String

 

3. 생성자(Constructor) 정보 찾기

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
32
33
34
35
36
37
38
39
40
41
package Java.reflection;
 
import java.lang.reflect.Constructor;
 
//Constructor 정보 가져오기
public class Reflection3_FindConstructor {
     
   public static void main(String[] args) throws Exception {
      
      //1. class 가져오기
      Class clazz = ExampleClass.class;
      
      //2. class 에서 Constructor 가져오기
      Constructor constructors[] = clazz.getDeclaredConstructors();
      
      for(Constructor c : constructors) {
         
         //1) 생성자명 가져오기
         System.out.println("name : " + c.getName());
         
         //2) 선언된 클래스명 가져오기
         System.out.println("class : " + c.getDeclaringClass());
         
         //3) parameter type 가져오기
         Class paramTypes[] = c.getParameterTypes();
         for(Class p : paramTypes) {
            System.out.println("param type : " + p);
         }
      
         //4) exception Type 가져오기
         Class exceptionTypes[] = c.getExceptionTypes();
         for(Class e : exceptionTypes) {
            System.out.println("exception type : " + e);
         }
         
         //5) 생성자에 return type은 존재하지 않으므로 getReturnType() 메소드는 없음 
         System.out.println();
      }
   }
}
 
cs

[결과]

name : Java.reflection.ExampleClass
class : class Java.reflection.ExampleClass

name : Java.reflection.ExampleClass
class : class Java.reflection.ExampleClass
param type : class java.lang.Object
exception type : class java.lang.NullPointerException

 

4. 필드 정보 찾기

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
32
33
34
35
36
37
38
39
package Java.reflection;
 
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
 
//Field 정보 가져오기
public class Reflection4_FindFields {
   
   public static void main(String[] args) throws Exception {
      
      //1. class 가져오기
      Class clazz = ExampleClass.class;
      
      //2. class 에서 Field 가져오기
      //Field fields[] = clazz.getFields();        //public modifier(접근제한자) field 만 가져올 수 있다
      Field fields[] = clazz.getDeclaredFields();  //private modifier field 도 가져올 수 있다
      
      for(Field f : fields) {
         
         //1) 필드명 가져오기
         System.out.println("name : " + f.getName());
         
         //2) 필드가 선언된 클래스명 가져오기
         System.out.println("class : " + f.getDeclaringClass());
         
         //3) 필드 타입 가져오기
         System.out.println("type : " + f.getType());
         
         //4) 필드의 접근제한자 가져오기 (int 형이며 Modifier.toString(mod) 로 string으로 바꿔줄 수 있음)
         int modifiers = f.getModifiers();
         System.out.println("modifiers int : " + modifiers);
         System.out.println("modifiers toString : " + Modifier.toString(modifiers));
         System.out.println("isPublic? : " + (modifiers == Modifier.PUBLIC));
         
         System.out.println();
      }
   }
}
 
cs

[결과]

name : CONSTANT_FIELD
class : class Java.reflection.ExampleClass
type : class java.lang.String
modifiers int : 26
modifiers toString : private static final
isPublic? : false

name : i
class : class Java.reflection.ExampleClass
type : int
modifiers int : 1
modifiers toString : public
isPublic? : true

생략..

 

5. 메소드 실행시키기 (invoke)

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package Java.reflection;
 
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
 
//https://kaspyx.tistory.com/80
 
//5. 메소드 실행시키기 invoke
public class Reflection5_invoke_1 {
   
   public Reflection5_invoke_1() {}
   
   public Reflection5_invoke_1(String a) {}
   
   public Reflection5_invoke_1(String a, Object b) {}
   
   public String addStrInt(String a, int b) {
      return a+b;
   }
   
   @SuppressWarnings({ "unchecked""rawtypes" })
   public static void main(String[] args) throws Exception {
      
      //1. class 가져오기
      Class clazz = Reflection5_invoke_1.class;
      
      Class paramTypes[] = new Class[2];
      paramTypes[0= String.class;
      paramTypes[1= Integer.TYPE;
      Method method = clazz.getMethod("addStrInt", paramTypes);   //* private modifier method 는 찾지 못한다
 
      Reflection5_invoke_1 methodObj = new Reflection5_invoke_1();
      Object argumentList[] = new Object[2]; 
      argumentList[0= "Str ";
      argumentList[1= new Integer(10);
      
      //java 문법은 보통 아래와 같이 S V O 
      //String rs = addStrInt("a", 10);
      //하지만, reflection 은 V.invoke(S, O)
      Object rs = method.invoke(methodObj, argumentList);
      
      System.out.println(rs);
      
   }
   
}
 
cs

[결과]

Str 10

 

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
32
33
34
35
36
37
38
39
40
41
42
package Java.reflection;
 
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
 
//https://kaspyx.tistory.com/80
 
//5. 메소드 실행시키기 invoke
public class Reflection5_invoke_2 {
   
   public Reflection5_invoke_2() {}
   
   public Reflection5_invoke_2(String a) {}
   
   public Reflection5_invoke_2(String a, Object b) {}
   
   public String addStrInt(String a, int b) {
      return a+b;
   }
   
   @SuppressWarnings({ "unchecked""rawtypes" })
   public static void main(String[] args) throws Exception {
      
      Method m = ExampleChildClass.class.getMethod("addStrInt"new Class[] {String.class, Integer.TYPE});
      String result = (String) m.invoke(new ExampleClass(), new Object[]{"Str "new Integer(10)});
      System.out.println(result);
      
      //위와 같다
      Method m3 = ExampleChildClass.class.getMethod("addStrInt"new Class[] {String.class, Integer.TYPE});
      String result3 = (String) m3.invoke(new ExampleClass(), new Object[]{"Str "new Integer(10)});
      System.out.println(result3);
      
      try {
         Method m2 = ExampleClass.class.getMethod("addStrInt"new Class[] {String.class, Integer.TYPE});
         String result2 = (String) m2.invoke(new ExampleSuperClass(), new Object[]{"Str "new Integer(10)});
         System.out.println(result2);
      } catch (IllegalArgumentException ie) {
         System.out.println(ie.getMessage());
      }
   }
}
 
cs

[결과]

Str 10
Str 10
object is not an instance of declaring class

 

6. 인스턴스 생성하기 (newInstance)

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package Java.reflection;
 
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
 
//https://kaspyx.tistory.com/80
 
//5. 메소드 실행시키기 invoke
public class Reflection6_newInstance {
   
   public Reflection6_newInstance() {}
   
   public Reflection6_newInstance(String a) {}
   
   public Reflection6_newInstance(String a, Object b) {}
   
   public String addStrInt(String a, int b) {
      return a+b;
   }
   
   @SuppressWarnings({ "unchecked""rawtypes" })
   public static void main(String[] args) throws Exception {
      
      Class clazz = Reflection6_newInstance.class;
      
      Class arguTypes[] = new Class[2];
      arguTypes[0= String.class;
      arguTypes[1= Integer.TYPE;
 
      Object params[] = new Object[2];
      params[0= "Str ";
      params[1= 10;
      
      Constructor myConstructor1 = clazz.getConstructor();     
      Object myObj = myConstructor1.newInstance();             
      Method m1 = clazz.getMethod("addStrInt", arguTypes); 
      String result1 = (String) m1.invoke(myObj, params);   
      System.out.println(result1);
      
      Constructor myConstructor2 = clazz.getConstructor(String.class);
      Object myObj2 = myConstructor2.newInstance("");
      Method m2 = clazz.getMethod("addStrInt", arguTypes);
      String result2 = (String) m2.invoke(myObj2, params);
      System.out.println(result2);
      
      Constructor myConstructor3 = clazz.getConstructor(String.class, Object.class);
      Object myObj3 = myConstructor3.newInstance(""new Object());
      Method m3 = clazz.getMethod("addStrInt", arguTypes);
      String result3 = (String) m3.invoke(myObj3, params);
      System.out.println(result3);
      
      Constructor myConstructor4 = clazz.getConstructor(new Class[]{String.class, Object.class});
      Object myObj4 = myConstructor4.newInstance(""new Object());
      Method m4 = clazz.getMethod("addStrInt"new Class[] {String.class, Integer.TYPE});
      String result4 = (String) m4.invoke(myObj4, new Object[] {"String " , 11});
      System.out.println(result4);
      
   }
}
 
cs

[결과]

Str 10
Str 10
Str 10
String 11

 

위의 모든 샘플 예제들은 github(https://github.com/develo-pyo)에 올려놓았습니다.

 

참고:

https://www.geeksforgeeks.org/reflection-in-java/

https://gyrfalcon.tistory.com/entry/Java-Reflection

 

반응형

+ Recent posts