用反射写实现set和get方法

需求:
利用反射完成以下方法 
 此方法可将obj对象中名为propertyName的属性的值设置为value.
 相当于用反射 写一个set方法
参数
 *  1.赋值对象
 *  2.属性名字
 *  3.给该属性赋值
 * 此方法可以获取obj对象中名为propertyName的属性的值
 *  相当于用反射 写一个get方法
 * 参数
 *  1.赋值对象
 *  2.要获取的属性名字

person类:

public class Person {
	public String name;
	private int age;
	public Person(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
	public Person() {
		super();
		// TODO Auto-generated constructor stub
	}
	// 私有构造方法
	private Person(int age, String name) {
		super();
		this.name = name;
		this.age = 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;
	}
	@Override
	public String toString() {
		return "[name=" + name + ", age=" + age + "]";
	}
	
	// 吃饭方法
	public void eat() {
		System.out.println("吃饭");
	}
	// 说话
	public void speak(String string) {
		System.out.println("说的是:" + string);
	}
	// 打游戏
	private int play(String game) {
		System.out.println("玩的是:" + game);
		return 123;
	}
}

主函数

public class Kll {
	public static void main(String[] args) throws Exception {
		Class<?> c = Class.forName("com.lanou3g.reflect.Person");
		Object object = c.newInstance();
		setObjectValue(object, "age", 20);
		System.out.println(object);
		getObjectValue(object, "age");
	}
	public static void setObjectValue(Object obj, String propertyName, Object value) throws Exception {
		// 获取Class文件对象
		Class<? extends Object> c = obj.getClass();
		
		// 从文件中获取属性
		Field field = c.getDeclaredField(propertyName);
		// 打开权限
		field.setAccessible(true);
		// 赋值
		field.set(obj, value);
		
	}
	// 取值
	public static Object getObjectValue(Object object, String propertyName) throws Exception {
		// 获取class文件对象
		Class<? extends Object> c = object.getClass();
		// 获取对应的属性
		Field field = c.getDeclaredField(propertyName);
		// 开启权限
		field.setAccessible(true);
		// 从对象中获取该field属性对应的值
		Object value = field.get(object);
		System.out.println(value);
		return value;
	}

}

猜你喜欢

转载自blog.csdn.net/KongLingLei_08225/article/details/82844459
今日推荐