Reflection? 객체를 통해 클래스의 정보를 분석해 내는 프로그램 기법
import java.lang.reflect.*;
import java.util.Vector;
public class ShowClassInfoMain {
public static void main(String [] args) {
Class c = Integer.class;
Class[] iface = c.getInterfaces(); //클래스내 포함된 인터페이스(1개 이상)
Constructor [] ctor = c.getConstructors(); //클래스내 포함된 생성자
Method [] m = c.getMethods(); //클래스내 포함된 메서드
Field[] f = c.getFields(); //클래스내 포함된 멤버필드
Class temp = c;
while( (temp=temp.getSuperclass()) != null ) { System.out.println(temp); } //클래스의 상위클래스(1개이므로)
for(int i=0; i<iface.length; i++) { System.out.println("interface[" + i + "]:" + iface[i]); }
for(int i=0; i<ctor.length; i++) { System.out.println("Constructor[" + i + "]:" + ctor[i]); }
for(int i=0; i<m.length; i++) { System.out.println("Method[" + i + "]:" + m[i]); }
for(int i=0; i<f.length; i++) { System.out.println("Field[" + i + "]:" + f[i]); }
}
}
#1 정적바인딩(다운캐스팅 가능) : 컴파일시 같은 디렉토리안에 존재해야함
헷갈려서.. 예를 몇개 써봅시다
#2 동적바인딩(다운캐스팅 불가능) : 컴파일때 필요 없다, 다른 컴퓨터에 있다, 웹서버에 있다.
그런데, 다운캐스팅을 못합니다. 때문에 해당 클래스의 메서드등을 쓰려면 여기서 리플렉션의 기법을 써야합니다.
import java.util.Vector;
public class ShowClassInfoMain {
public static void main(String [] args) {
Class c = Integer.class;
Class[] iface = c.getInterfaces(); //클래스내 포함된 인터페이스(1개 이상)
Constructor [] ctor = c.getConstructors(); //클래스내 포함된 생성자
Method [] m = c.getMethods(); //클래스내 포함된 메서드
Field[] f = c.getFields(); //클래스내 포함된 멤버필드
Class temp = c;
while( (temp=temp.getSuperclass()) != null ) { System.out.println(temp); } //클래스의 상위클래스(1개이므로)
for(int i=0; i<iface.length; i++) { System.out.println("interface[" + i + "]:" + iface[i]); }
for(int i=0; i<ctor.length; i++) { System.out.println("Constructor[" + i + "]:" + ctor[i]); }
for(int i=0; i<m.length; i++) { System.out.println("Method[" + i + "]:" + m[i]); }
for(int i=0; i<f.length; i++) { System.out.println("Field[" + i + "]:" + f[i]); }
}
}
#1 정적바인딩(다운캐스팅 가능) : 컴파일시 같은 디렉토리안에 존재해야함
헷갈려서.. 예를 몇개 써봅시다
ex1) Class c0 = Data.class; Object obj = c0.newInstance(); Data d = (Data)obj; d.sayHello(); //obj.sayHello는 안됨, 다운캐스팅 후 사용 |
ex2) ex1이어서.. Class c2 = d.getClass(); Data d2 = (Data)c2.newInstance(); |
ex3) String str = new String("Hello"); Class c1 = String.class; Object obj = c1.newInstance(); |
ex4) Class c2 = new String("Hello").getClass(); Object obj = c2.newInstance(); |
#2 동적바인딩(다운캐스팅 불가능) : 컴파일때 필요 없다, 다른 컴퓨터에 있다, 웹서버에 있다.
ex1) 순서1. 웹 서버에 존재하는 DynamicData.class 파일 다운로드 URL url = new URL("http://www.jabook.org/DynamicData.class"); InputStream is = url.openStream(); FileOutputStream fos = new FileOutputStream("DynamicData.class"); 순서2. DynamicData.class 로딩 Class c = Class.forName("DynamicData"); Object obj = c.newInstance(); |
ex2) 순서1. URLClassLoader 생성하기 URL[] urlArray = {new URL("http://www.jabook.org:80/")}; URLClassLoader cLoader = new URLClassLoader(urlArray); 순서2. URLClassLoader를 이용해서 Class 클래스 로딩하기 Class c = cLoader.loadClass("DynamicData"); Object obj = c.newInstance(); |