Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- port
- import
- vscode
- resource
- JavaScript
- netsh
- VirtualBox
- GIT
- tomcat
- context
- 단축키
- lsof
- bash
- 네트워크
- profile
- Windows 10
- maVen
- IntelliJ
- web.xml
- Source
- find
- grep
- xargs
- Mac
- Eclipse
- ssh
- Quartz
- Windows
- 줄바꿈 문자
- plugin
Archives
- Today
- Total
develog
Reflection 본문
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