Discuss / Java / 练习

练习

Topic source
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 n = p.getClass().getDeclaredMethod("setName", String.class);
		Method a = p.getClass().getDeclaredMethod("setAge", int.class);
		
		n.invoke(p, name);
		a.invoke(p, age);
		
		System.out.println(p.getName()); // "Xiao Ming"
		System.out.println(p.getAge()); // 20
	}
}

class Person {

	private String name;
	private int age;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

}

  • 1

Reply