-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReflectionExample.java
More file actions
78 lines (65 loc) Β· 2.42 KB
/
ReflectionExample.java
File metadata and controls
78 lines (65 loc) Β· 2.42 KB
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package ch12.sec11.exam02;
import java.lang.reflect.*;
/* λ©€λ² μ 보 μ»κΈ° */
public class ReflectionExample {
public static void main(String[] args) {
Class clazz = Car.class;
System.out.println("[μμ±μ μ 보]");
Constructor[] constructors = clazz.getDeclaredConstructors();
for (Constructor constructor : constructors) {
System.out.print(constructor.getName() + "("); // μμ±μμ μ΄λ¦μ λ¬Έμμ΄λ‘ λ°ν
Class[] parameterTypes = constructor.getParameterTypes();
printParameters(parameterTypes);
System.out.println(")");
}
System.out.println();
System.out.println("[νλ μ 보]");
// Field ν΄λμ€ λλ μΈν°νμ΄μ€μ λ¨μΌ νλμ λν μ 보μ λμ λ©μλ μ 곡
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
// getType(): Class κ°μ²΄κ° λνλ΄λ νλμ λν΄ μ μΈλ μ νμ μλ³νλ κ°μ²΄ λ°ν
// getName(): μ΄ κ°μ²΄κ° λνλ΄λ νλμ μ΄λ¦μ λ°ν
System.out.print(field.getType() + " " + field.getName());
}
System.out.println();
System.out.println("[λ©μλ μ 보]");
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
// κ°μ²΄κ° λνλ΄λ methodμ μ΄λ¦μ Methodλ‘ λ°ν
System.out.print(method.getName() + "(");
Class[] parameterTypes = method.getParameterTypes();
printParameters(parameterTypes);
System.out.println(")");
}
}
/* μμ±μ λ° λ©μλμ λ§€κ°λ³μ μ 보λ₯Ό μΆλ ₯ */
private static void printParameters(Class[] parameterTypes) {
for (int i = 0; i < parameterTypes.length; i++) {
System.out.print(parameterTypes[i].getName());
if (i < (parameterTypes.length - 1)) {
System.out.print(",");
}
}
}
}
class Car {
private String model;
private String owner;
public Car() {
}
public Car(String model, String owner) {
this.model = model;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
}