Discuss / Java / 作业

作业

Topic source

何以忘言i

#1 Created at ... [Delete] [Delete and Lock User]
package com.itranswarp.learnjava;
import java.lang.reflect.Field;

/**
 * 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: 利用反射给name和age字段赋值:
		Class cls = p.getClass();
		Field[] fs = cls.getDeclaredFields();
		for(Field f : fs) {
			f.setAccessible(true);
			switch(f.getName()) {
			case("name"):{
				f.set(p, name);
				break;
			}
			case("age"):{
				f.set(p, age);
				break;
			}
			}
		}
		System.out.println(p.getName()); // "Xiao Ming"
		System.out.println(p.getAge()); // 20
	}
}


  • 1

Reply