Person类:
package helloworld;
public class Person {
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String secondName) {
this.lastName = secondName;
}
public String toString() {
return "First name: " + firstName + ", Last name: " + lastName;
}
}
测试代码:
package helloworld;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.LinkedHashMap;
import java.util.Map;
public class MyMain {
static Map<String, String> methods = new LinkedHashMap<String, String>();
static {
methods.put("firstName", "setFirstName");
methods.put("lastName", "setLastName");
}
public static void main(String[] args) {
Person person = new Person();
updateField(person, "firstName", "The First Name");
updateField(person, "lastName", "The Last Name");
System.out.println(person);
}
private static void updateField(Person person, String fieldName, String fieldValue) {
try {
String methodName = methods.get(fieldName);
Method method = null;
method = Person.class.getMethod(methodName, String.class);
//method = person.getClass().getMethod(methodName, String.class);
System.out.println(method);
method.invoke(person, fieldValue);
} catch (NoSuchMethodException | SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
要点:在getMethod后面的参数类型需要加上,否则出现java.lang.NoSuchMethodException错误。——也好理解,如果不加这个参数类型列表,就没法支持函数重载了。