티스토리 뷰

동적으로 다른 클래스의 메서드와 필드값을 불러와서 사용해야 하는 경우, Java Reflection을 활용하면 가능하다.

 

// 메서드-------------------------------------------------------------------------
Method getSomethingMethod = ClassName.getClass().getDeclaredMethod("getSomething", String.class);
getSomethingMethod.setAccessible(true); // private 함수 접근 허용.
String someString = (String) getSomethingMethod.invoke("something");


// 불러올 메서드가 static일 때.
Method getSomethingMethod = ClassName.class.getDeclaredMethod("getSomething", MemberVo.class, String.class); // getClass() 대신 class
getSomethingMethod.setAccessible(true); // private 접근 허용
String someString = (String) getSomethingMethod.invoke(null, memberVo, "something"); // null
//--------------------------------------------------------------------------------

// 필드---------------------------------------------------------------------------
Field pathField = ClassName.getClass().getDeclaredField("urlPath");
if(!pathField.isAccessible()) pathField.setAccessible(true); // private 접근 허용
String pathVal = (String) pathField.get(ClassName.class);

// 불어올 필드가 static일 때.
Field pathField = ClassName.class.getDeclaredField("urlPath");
if(!pathField.isAccessible()) pathField.setAccessible(true); // private 접근 허용
String pathVal = (String) pathField.get(ClassName.class);
//--------------------------------------------------------------------------------

 

 

 

 

 

 

댓글
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/04   »
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
글 보관함