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;
}
}
CopyUtil
最新推荐文章于 2024-03-04 16:59:31 发布