*/ import java.lang.reflect.Method; 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方法: Class cls = p.getClass(); Method nameMethod = cls.getMethod("setName", String.class); Method ageMethod = cls.getMethod("setAge", int.class); nameMethod.invoke(p, name); ageMethod.invoke(p, age); System.out.println(p.getName()); // "Xiao Ming" System.out.println(p.getAge()); // 20 } }
Sign in to make a reply
Lumen.