Discuss / Java / 交作业

交作业

Topic source

Young-96

#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方法:
        Method m1 = p.getClass().getMethod("setName", String.class);
        m1.invoke(p, name);

        Method m2 = p.getClass().getMethod("setAge", int.class);
        m2.invoke(p, age);

        System.out.println(p.getName()); // "Xiao Ming"
        System.out.println(p.getAge()); // 20
    }
}


  • 1

Reply