-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathReflectionTest.java
More file actions
51 lines (44 loc) · 1.14 KB
/
Copy pathReflectionTest.java
File metadata and controls
51 lines (44 loc) · 1.14 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
package inverview.reflection;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
public class ReflectionTest {
public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {
Person person = new Person("Doug", "Sparling", 31);
Map<String, Object> values = new HashMap<>();
for (Field field : person.getClass().getDeclaredFields()) {
values.put(field.getName(), field.get(person));
}
// prints {firstName=Doug, lastName=Sparling, age=31}
System.out.println(values);
}
}
class Person{
String firstName;
String lastName;
int age;
public Person(String firstName, String lastName, int age) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}