java.lang.reflect.Method 中getWriteMethod() 的使用方法

使用getWriteMethod() 为类的属性赋值。

一、普通类如下:

public class MyBean {
	private String id = null;
	private String userName = null;
	
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	
}

 

二、测试类如下:

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class MethodWrite {
	
	private MyBean beanObj = null;
	
	private BeanInfo bBeanObjInfo = null;
	
	public void TestMethodInvoke(){
		Map userMap = new HashMap();
		userMap.put("id", "1001");
		userMap.put("userName", "isoftstone");
		
		try{
			//实例化一个Bean
			beanObj = new MyBean();
			//依据Bean产生一个相关的BeanInfo类
			bBeanObjInfo = Introspector.getBeanInfo(beanObj.getClass());
			
			PropertyDescriptor[] propertyDesc = bBeanObjInfo.getPropertyDescriptors();
			for (int i = 0; i < propertyDesc.length; i++) {
				if (propertyDesc[i].getName().compareToIgnoreCase("class")==0) continue;
				//System.out.print(propertyDesc[i].getName());
				String strValue = (String)userMap.get((String)propertyDesc[i].getName());
				//System.out.println(strValue);
				
				if(strValue != null){
					Object[] oParam = new Object[]{};
					Method mr = propertyDesc[i].getWriteMethod();
					if( mr != null){
						oParam = new String[]{(strValue)};
						try{
							//注意这里的参数。
							mr.invoke(beanObj, oParam);
						}catch(IllegalArgumentException iea){
							System.out.println("参数错误。");
							iea.printStackTrace();
						}
						
					}
				}
				
			}
			
			System.out.println(beanObj.getId());
			System.out.println(beanObj.getUserName());
			
		}catch(IntrospectionException e){
			System.out.println("Java Bean 内省异常。");
		}catch(IllegalAccessException ia){
			System.out.println("参数异常。");
			ia.printStackTrace();
		}catch(InvocationTargetException ie){
			System.out.println("invode异常。");
			ie.printStackTrace();
		}
		
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		new MethodWrite().TestMethodInvoke();
	}

}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值