Discuss / Java / 作业

作业

Topic source

Lumen.

#1 Created at ... [Delete] [Delete and Lock User]
 */
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
    }
}


  • 1

Reply