Class 객체를 이용하면 클래스의 생성자, 필드, 메소드 정보를 알아낼 수 있다. 이것을 리플렉션(Reflection)이라고 한다. Class 객체는 리플렉션을 위해 getDeclaredConstructors(), getDeclaredFields(), getDeclaredMethods()를 제공하고 있다.
Constructor[] constructors =clazz.getDeclaredConstructors();
Field[] fields =clazz.getDeclaredFields();
Method[] methods=clazz.getDeclaredMethod();
메소드 이름에서 알 수 있듯이 세 메소드는 각각 Constructor 배열, Field 배열, Method 배열을 리턴한다. Constructor, Field, Method 클래스는 모두 java, lang, reflect 패키지에 소속되어 있다. getDeclaredFields(), getDeclaredMethods() 는 클래스에 선언된 멤버만 가져오고 상속된 멤버는 가져오지 않는다. 만약 상속된 멤버도 얻고 싶다면 getFields(), getMethods()를 이용해야 한다. 단 getFields(), getMethods()를 이용해야 한다. 단 getFields(), getMethods() 는 public 멤버만 가져온다. 다음은 Car 클래스에서 선언된 생성자, 필드, 메소드의 정보를 얻고 출력한다.
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 |
package egoing;
import java.lang.reflect.Constructor;
public class ReflectionExample {
public static void main(String[] args) throws Exception { Class clazz =Class.forName("egoing.Car"); System.out.println(clazz.getName());
System.out.println("[생성자 정보]"); Constructor[] constructors =clazz.getDeclaredConstructors(); for(Constructor constructor : constructors){
System.out.print(constructor.getName() + "("); Class[] parameters =constructor.getParameterTypes(); printParameters(parameters); System.out.println(")");
}
}
private static void printParameters(Class[] parameters){ for(int i=0; i<parameters.length; i++){ System.out.println(parameters[i].getName()); if(i<parameters.length-1){ System.out.println(","); } } }
}
|
cs |
egoing.Car
[생성자 정보]
egoing.Car()
댓글 ( 4)
댓글 남기기