public class Main {
public static void main(String[] args) throws Exception {
String name = "Xiao Ming";
int age = 20;
Person p = new Person();
// TODO: 利用反射调用setName和setAge方法:
Method d = p.getClass().getMethod("setName", String.class);
d.invoke(p, name);//显示The method getMethod(String, Class[]) in the type Class is not applicable for the arguments (String, Class<T>)
Method d2 = p.getClass().getMethod("setAge", int.class);
d2.invoke(p, age);
System.out.println(p.getName()); // "Xiao Ming"
System.out.println(p.getAge()); // 20
}
import java.lang.reflect.*;
也可以链式编程,不用再导包
Person.class.getMethod("setName", String.class).invoke(p, name);
Sign in to make a reply
用户2059306608
public class Main {
public static void main(String[] args) throws Exception {
String name = "Xiao Ming";
int age = 20;
Person p = new Person();
// TODO: 利用反射调用setName和setAge方法:
Method d = p.getClass().getMethod("setName", String.class);
d.invoke(p, name);//显示The method getMethod(String, Class[]) in the type Class is not applicable for the arguments (String, Class<T>)
Method d2 = p.getClass().getMethod("setAge", int.class);
d2.invoke(p, age);
System.out.println(p.getName()); // "Xiao Ming"
System.out.println(p.getAge()); // 20
}
}