A Case Using Java Reflection

We have a class Person:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.reflection;

public class Person {
private String name;
private Integer age;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}
}

We also have a class Student:

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
package com.reflection;

public class Student {
private String name;
private Integer age;
private String number;
private String grade;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}

public String getNumber() {
return number;
}

public void setNumber(String number) {
this.number = number;
}

public String getGrade() {
return grade;
}

public void setGrade(String grade) {
this.grade = grade;
}
}

The class Person and Student have same fields name of type String and age of Type Integer. Therefore, we can set a student’s fields using a person’s counterpart fields:

1
2
3
4
5
6
7
8
9
10
11
12
13
package com.reflection;

public class Main {
public static void main(String[] args) {
Person person = new Person();
person.setName("Eric");
person.setAge(24);

Student student = new Student();
student.setName(person.getName());
student.setAge(person.getAge());
}
}

A more efficient way is to use reflection:

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
package com.reflection;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Main {
public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {
Person person = new Person();
person.setName("Eric");
person.setAge(24);

Student student = new Student();

Class<? extends Person> personClass = person.getClass();
Class<? extends Student> studentClass = student.getClass();

Method[] personClassDeclaredMethods = personClass.getDeclaredMethods();
Method[] studentClassDeclaredMethods = studentClass.getDeclaredMethods();

for (Method personMethod : personClassDeclaredMethods) {
if (personMethod.getName().contains("get")) {
String setterName = "set" + personMethod.getName().substring(3);// e.g. getAge => setAge
Object getterValue = personMethod.invoke(person);// i.e. person.getAge()
for (Method studentMethod : studentClassDeclaredMethods) {
if (studentMethod.getName().equals(setterName)) {
studentMethod.invoke(student, getterValue);// i.e. student.setAge(getterValue)
}
}
}
}
}
}