자바에서 Class 클래스는 클래스의 정보(메타데이터)를 다루는데 사용된다.
개발자는 실행중인 자바 어플리케이션 내에 필요한 클래스의 속성, 메서드에 관한 정보를 조회하고 조작할 수 있다.
package test.clazz;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class ClassMetaMain {
static void main(String[] args) throws Exception {
// Class 조회
Class clazz = String.class; // 1. 클래스에서 조회
Class clazz1 = new String().getClass(); // 2. 인스턴스에서 조회
Class clazz2 = Class.forName("java.lang.String"); // 3. 문자열로 조회
// 모든 필드 출력
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
System.out.println("field: " + field.getType() + " " + field.getClass());
}
// 모든 메서드 출력
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
System.out.println("method: " + method);
}
// 상위 클래스 출력
System.out.println("SuperClass: " + clazz.getSuperclass().getName());
// 인터페이스 출력
Class[] interfaces = clazz.getInterfaces();
for (Class i : interfaces) {
System.out.println("Interface: " + i.getName());
}
}
}
Class 클래스에는 클래스의 모든 정보가 들어가 있다.
이 정보를 기반으로 인스턴스를 생성하거나, 메서드를 호출할 수 있다.
package test.clazz;
public class Hello {
public String hello() {
return "Hello";
}
}
package test.clazz;
public class ClassCreateMain {
static void main(String[] args) throws Exception {
Class helloClass = Hello.class;
// Class helloClass = Class.forName("lang.clazz.Hello");
Hello hello = (Hello) helloClass.getDeclaredConstructor().newInstance();
String result = hello.hello();
System.out.println(hello);
System.out.println(result);
}
}
Class를 사용하면 클래스의 메타정보를 기반으로 메서드, 필드, 생성자 등을 조회하고, 이를 통해 인스턴스를 생성하거나 메서드를 호출하는 작업을 할 수 있다.
이런 작업을 리플렉션이라고 한다.
최신 프레임워크는 이런 기능을 적극 활용한다.
지금은 Class가 뭔지, 어떤 기능이 있는지 정도만 알아두자.
Class는 클래스의 설계도 정보를 담고 있고, 리플렉션은 그 정보를 실행 중에 분석하고 조작하는 기술이다