Discuss / Java / 作业

作业

Topic source

何以忘言i

#1 Created at ... [Delete] [Delete and Lock User]
package com.itranswarp.learnjava;
import java.lang.reflect.Method;
/**
 * Learn Java from https://www.liaoxuefeng.com/
 * 
 * @author liaoxuefeng
 */
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 h1 = Person.class.getMethod("setName", String.class);
		h1.invoke(p, "Xiao Ming");
		Method h2 = Person.class.getMethod("setAge", int.class);
		h2.invoke(p, 20);
		System.out.println(p.getName()); // "Xiao Ming"
		System.out.println(p.getAge()); // 20
	}
}


  • 1

Reply