JAVA Basic 강의자료] Reflection의 실제 구현(2)
JAVA Basic 강의자료] Reflection의 실제 구현(2)
실무개발자를위한 실무교육 전문교육센터학원
www.oraclejava.co.kr에 오시면 보다 다양한 강좌를 보실 수 있습니다.
Reflection의 실제 구현(2)
*매개변수 없는 메서드 호출
<소스코드>
import java.awt.*;
import java.lang.reflect.*;
public class MethodInvoke1 {
public static void main(String[] arg) throws
ClassNotFoundException,
NoSuchFieldException, IllegalAccessException,
NoSuchMethodException, IllegalAccessException,
InvocationTargetException {
Class c = String.class;
Method m = c.getMethod("length", null);
String s = "Hello World";
Object result = m.invoke(s, null);
System.out.println(result.toString());
}
}
*매개변수 있는 메서드 호출
<소스코드>
import java.awt.*;
import java.lang.reflect.*;
public class MethodInvoke2 {
public static void main(String[] arg) throws
ClassNotFoundException, NoSuchFieldException,
IllegalAccessException, NoSuchMethodException,
InvocationTargetException {
Class c = String.class;
Class[] parameterTypes = new Class[] {int.class, int.class};
Method m = c.getMethod("substring", parameterTypes);
Object[] parameters = new Object[] {new Integer(6), new
Integer(11)};
String s = "Hello World";
Object result = m.invoke(s, parameters);
System.out.println(result.toString());
}
}
*멤버필드 값 알아내기
<소스코드>
import java.awt.*;
import java.lang.reflect.*;
public class GettingField {
public static void main(String[] arg) throws
ClassNotFoundException,
NoSuchFieldException,IllegalAccessException {
Class c = Class.forName("java.awt.Point");
Field f = c.getField("x");
Point p = new Point(100,200);
Object x = f.get(p);
System.out.println(x.toString());
}
}
'자바 > Java공부하기' 카테고리의 다른 글
JAVA Basic 강의자료] Spring MVC 개발 (0) | 2016.09.21 |
---|---|
JAVA Basic 강의자료] Spring 3.2 & MyBatis 목차 (0) | 2016.09.21 |
JAVA Basic 강의자료] Reflection의 실제 구현(1) (0) | 2016.09.20 |
JAVA Basic 강의자료] Class class 사용 예제 (0) | 2016.09.20 |
JAVA Basic 강의자료] Class class 로딩 (0) | 2016.09.20 |