JavaBean 内省方法修改某个类中域的值

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.*;

public class IntrospectionTest {
	
	public static void main(String[] args) 
			throws IntrospectionException, IllegalAccessException,
			IllegalArgumentException, InvocationTargetException{

		Person p = new Person(300, "Panda", 20);
		
		String property ="name";  //这里是要设置的名称,与类中的
								  //某个域名称要一值,因为只是你需要修改的域
		
		getMethod(p, property);  //获得name的域的值
		Object name = "Tiger";   
		setMethod(p, property, name); //修改name的值为Tiger		
	}

	/**
	 * 此方法是用javabean内省方式,修改域中的数据
	 * 步骤:
	 * 1、利用 PropertyDescriptor(String propertyName, Class<?> beanClass) 
	           通过调用 getFoo 和 setFoo 存取方法,为符合标准 Java 约定的属性构造一个
		PropertyDescriptor。
                    第一个参数传递 需要修改的名称,第二个参数传递需要修改类的Class,不需要实例化
       2、使用getWriteMethod()得到一个类中的get方法,对应构造中propertyName的域
       3、使用 Object invoke(Object obj, Object... args)对带有指定参数的指定对象
       	调用由此 Method 对象表示的底层方法。 
       	第一个参数是实例化以后需要修改的对象,第二个参数是需要修改的值。

	 * @param p 代表实例化的一个person类
	 * @param property 需要修改的域
	 * @param name 修改后的域
	 * @throws IntrospectionException
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 * 
	 */
	private static void setMethod(Person p, String property, Object name)
			throws IntrospectionException, IllegalAccessException,
			InvocationTargetException {
		PropertyDescriptor prop = new PropertyDescriptor(property, Person.class);
		Method setMth = prop.getWriteMethod();
		setMth.invoke(p, name);
		getMethod(p, property);
	}

	/**
	 * 与上述方法类似,invoke方法更简单,因为get方法,只是获取,所以不需要传递更新值
	 * @param p
	 * @param property
	 * @throws IntrospectionException
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 */
	private static void getMethod(Person p, String property)
			throws IntrospectionException, IllegalAccessException,
			InvocationTargetException {
		PropertyDescriptor prop = new PropertyDescriptor(property, Person.class);
		Method readMth = prop.getReadMethod();
		Object retVal = readMth.invoke(p);
		System.out.println(retVal);
	}
}

下面是一个普通的JavaBean文件,提供3个域:

public class Person {
	
	private int age;
	private String name;
	private long id;
	
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public Person(int age, String name, long id) {
		super();
		this.age = age;
		this.name = name;
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public long getId() {
		return id;
	}
	public void setId(long id) {
		this.id = id;
	}
	
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值