develog

Reflection 본문

Dev/Java

Reflection

냐옴 2012. 11. 6. 22:29

 

1. 클래스 얻기

 

  • Object.getClass()
UserVo vo = new UserVo();
System.out.println(vo.getClass());
  • .class
System.out.println(UserVo.class);
  • Class.forName("")
try {
	System.out.println(Class.forName("vo.UserVo"));
} catch (ClassNotFoundException e) {
	e.printStackTrace();
}

 

 

2. private field 셋팅

public class UserVo {

    private String name;

    public String getName() {
        return name;
    }

}
public static void main(String[] args) {
    
    try {
        
        Class clazz = Class.forName("UserVo");
        Field field = clazz.getDeclaredField("name");
        field.setAccessible(true);

        UserVo vo = (UserVo) clazz.newInstance();
        field.set(vo, "TEST");

        String value = (String) vo.getName();
        System.out.println(value);

    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    }
    
}

 

    

3. private method 호출

public class UserVo {

    private String getName() {
        return "TEST";
    }

}
public static void main(String[] args) {
    try {

        Class clazz = Class.forName("UserVo");
        Method method = clazz.getDeclaredMethod("getName");
        method.setAccessible(true);

        UserVo vo = (UserVo) clazz.newInstance();
        String value = (String) method.invoke(vo);
        System.out.println(value);

    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }
}
 
 
4. private constructor 인스턴스 만들기
public class UserVo {
    
    private UserVo() {
    }
    
}​
public static void main(String[] args) {
    try {

        Class clazz = Class.forName("UserVo");
        Constructor constructor = clazz.getDeclaredConstructor();
        constructor.setAccessible(true);
        UserVo vo = (UserVo)constructor.newInstance();
        System.out.println(vo);

    } catch (Exception e) {
        e.printStackTrace();
    }
}
 

 

'Dev > Java' 카테고리의 다른 글

Annotation 정의  (0) 2012.11.06
Annotation 종류  (0) 2012.11.06
Reflection Test  (0) 2012.11.06
[Tomcat] jsp cache clear  (0) 2012.10.08
timestamp 출력  (0) 2012.09.21
Comments