invoke copy bean

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;
}

你可能感兴趣的:(bean)