Programming/Java
Reflection
SharingWorld
2018. 4. 2. 10:32
package io.thethelab.data;
import java.lang.reflect.Method;
// Reflection의 문제점
// : 잘못 사용한 경우, 성능이 느리다.
class User {
private String name;
private int age;
public User() {
this("Unnamed", 0);
}
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
// Java
// Class의 Class 타입 - Reflection / Introspection
// 특정한 클래스의 Class를 얻는 방법 3가지
// 1. class
// 2. 객체
// 3. 문자열
// 용도 3가지
// 1. 객체의 타입을 비교할 때 사용한다.
// instanceOf: 계층 구조
// class: 타입
// 2. 동적(dynamic: Runtime) 생성
//
// 3. 다양한 정보를 얻어낼 수 있다.
// IDE가 지원하는 범위가 다르다.
// User -> io.thethelab.data.User;
class Mother extends User {
public void say() {
System.out.println("Mother said");
}
}
public class Program_0321 {
static void foo(User u) {
// u가 mother 객체인지 판단해야 한다.
// if (u instanceof Mother) {
if (u.getClass() == Mother.class) {
Mother m = (Mother) u;
m.say();
}
}
public static void main(String[] args) throws ClassNotFoundException {
foo(new User("Tom", 42));
foo(new Mother());
User user = new User("Tom", 42);
// 1. 클래스
Class clazz1 = User.class;
// 2. 객체
Class clazz2 = user.getClass();
// 3. 문자열: 실패할 수 있다. (ClassNotFoundException)
Class clazz3 = Class.forName("io.thethelab.data.User");
// Intent intent = new Intent(this, MainActivity.class);
// startActivity(intent);
// 동적 생성
// Framework
Class clazz = Mother.class; // User.class or Mother.class
try {
clazz.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
clazz = User.class;
Method[] methods = clazz.getMethods();
for (Method e : methods) {
System.out.println(e.getName());
}
}
}