现在的位置: 首页 > 综合 > 正文

inovke copy bean

2013年09月15日 ⁄ 综合 ⁄ 共 863字 ⁄ 字号 评论关闭
public Object copyBean(Object source) throws Exception{
		String getMethodName = "";
		String setMethodName = "";
		Method getMethod = null;
		Method setMethod = null;
		Class<? extends Object> sClass = source.getClass();
		//用对象类型创建对象并获得对象的一个拷贝
		Object destination = sClass.getConstructor(new Class[]{}).newInstance(new Object[]{}) ;
		
		Class<? extends Object> dClass = destination.getClass();
		Field[] fields = sClass.getDeclaredFields();
		for(int i = 0; i < fields.length; i++){
			getMethodName = "get" + fields[i].getName().substring(0,1).toUpperCase() + fields[i].getName().substring(1);
			setMethodName = "set" + fields[i].getName().substring(0,1).toUpperCase() + fields[i].getName().substring(1);
			getMethod = sClass.getMethod(getMethodName, new Class[]{});
			setMethod = dClass.getMethod(setMethodName, new Class[]{fields[i].getType()});
			Object value = getMethod.invoke(source, new Object[]{});
			setMethod.invoke(destination, new Object[] {value});
		}
		return destination;
	}


抱歉!评论已关闭.