Discuss / Java / 练习

练习

Topic source
package com.itranswarp.learnjava;

import java.lang.reflect.Field;

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<?> c = p.getClass();
		Field f = c.getDeclaredField("name");
		Field a = c.getDeclaredField("age");
		
		f.setAccessible(true);
		a.setAccessible(true);
		f.set(p,"Xiao Hong");
		a.set(p,23);
		
		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