Java Reflect 활용하기
최종수정일: 2015.04.14
클래스의 정보 가져오기
Class<'Question'> clazz = Question.class; //클래스출력 logger.debug("Class: "+clazz.getName()); //필드출력 Field[] fieldArray = clazz.getDeclaredFields(); for (Field field : fieldArray) { logger.debug("Field: "+field.getName()); } //생성자출력 Constructor[] constArray = clazz.getDeclaredConstructors(); for (Constructor constructor : constArray) { logger.debug("Constructor: "+constructor.getName()+" \\ Parameter: "+constructor.getParameterCount()); } //메서드출력 Method[] methodArray = clazz.getDeclaredMethods(); for (Method method : methodArray) { logger.debug("Method: "+method.getName()); logger.debug("Parameter: "+method.getParameterCount()); }
클래스의 메서드 실행하기: 인자(arguments)가 없는경우
Class<'MyClass'> clazz = MyClass.class; Method[] methods = clazz.getDeclaredMethods(); for (Method method : methods) { MyClass my = clazz.newInstance(); method.invoke(my); }
Annotation을 활용하여 특정 메서드만 실행하기
Class<'MyClass'> clazz = MyClass.class;
Method[] annotMethods = clazz.getDeclaredMethods();
MyClass my = clazz.newInstance();
for (Method method : annotMethods) {
Annotation[] annotations = method.getDeclaredAnnotations();
for (Annotation annotation : annotations) {
//실행하고 싶은 어노테이션이 @MyAnnotation 일때
if(annotation.annotationType() == MyAnnotation.class) {
method.invoke(my);
}
}
}