CopyUtil

import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;

public class CopyUtil {

	public static boolean isItomObj(Class cls) {
		if (cls.isPrimitive() || cls.isEnum() || cls == BigDecimal.class
				|| cls == BigInteger.class || cls == String.class
				|| cls == Integer.class || cls == Boolean.class
				|| cls == Byte.class || cls == Character.class
				|| cls == Short.class || cls == Long.class
				|| cls == Float.class || cls == Double.class) {
			return true;
		}
		return false;
	}
	
	public static Object copy(Object obj){
		if(obj == null){
			return null;
		}
		if(obj instanceof Class || isItomObj(obj.getClass())){
			return obj;
		}
		if(obj instanceof Collection){
			return copy((Collection)obj);
		}else if(obj instanceof Map){
			return copy((Map)obj);
		}else if(obj.getClass().isArray()){
			return copy((Object[]) obj);
		}else{
			try {
				Method method = obj.getClass().getMethod("clone");
				if(!method.isAccessible()){
					method.setAccessible(true);
				}
				return (Object)method.invoke(null);
			} catch (Exception e) {
				return null;
			}
		}
	}
	
	public static Collection copy(Collection obj){
		if(obj == null){
			return null;
		}
		Collection copy = null;
		try {
			copy = (Collection)obj.getClass().newInstance();
		} catch (InstantiationException | IllegalAccessException e) {
			return null;
		}
		for(Iterator it = obj.iterator(); it.hasNext();){
			copy.add(copy(it.next()));
		}
		return copy;
	}
	
	public static Object[] copy(Object[] obj){
		if(obj == null){
			return null;
		}
		Object[] copy = (Object[]) Array.newInstance(obj.getClass().getComponentType(), obj.length);
		for(int i = 0; i < obj.length; i++){
			copy[i] = copy(obj[i]);
		}
		return copy;
	}
	
	public static Map copy(Map obj){
		if(obj == null){
			return null;
		}
		Map copy = null;
		Object key = null;
		try {
			copy = obj.getClass().newInstance();
			for(Iterator it = obj.entrySet().iterator(); it.hasNext(); it.next()){
				key = it.next();
				copy.put(copy(key), copy(obj.get(key)));
			}
		} catch (InstantiationException | IllegalAccessException e) {
			return null;
		}
		return copy;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值