Java对象之间的深度复制拷贝
/*
* Copyright (c) 1995, 2011, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/ package java.lang; /**
* {@code RuntimeException} is the superclass of those
* exceptions that can be thrown during the normal operation of the
* Java Virtual Machine.
*
* <p>{@code RuntimeException} and its subclasses are <em>unchecked
* exceptions</em>. Unchecked exceptions do <em>not</em> need to be
* declared in a method or constructor's {@code throws} clause if they
* can be thrown by the execution of the method or constructor and
* propagate outside the method or constructor boundary.
*
* @author Frank Yellin
* @jls 11.2 Compile-Time Checking of Exceptions
* @since JDK1.0
*/
public class RuntimeException extends Exception {
static final long serialVersionUID = -7034897190745766939L; /** Constructs a new runtime exception with {@code null} as its
* detail message. The cause is not initialized, and may subsequently be
* initialized by a call to {@link #initCause}.
*/
public RuntimeException() {
super();
} /** Constructs a new runtime exception with the specified detail message.
* The cause is not initialized, and may subsequently be initialized by a
* call to {@link #initCause}.
*
* @param message the detail message. The detail message is saved for
* later retrieval by the {@link #getMessage()} method.
*/
public RuntimeException(String message) {
super(message);
} /**
* Constructs a new runtime exception with the specified detail message and
* cause. <p>Note that the detail message associated with
* {@code cause} is <i>not</i> automatically incorporated in
* this runtime exception's detail message.
*
* @param message the detail message (which is saved for later retrieval
* by the {@link #getMessage()} method).
* @param cause the cause (which is saved for later retrieval by the
* {@link #getCause()} method). (A <tt>null</tt> value is
* permitted, and indicates that the cause is nonexistent or
* unknown.)
* @since 1.4
*/
public RuntimeException(String message, Throwable cause) {
super(message, cause);
} /** Constructs a new runtime exception with the specified cause and a
* detail message of <tt>(cause==null ? null : cause.toString())</tt>
* (which typically contains the class and detail message of
* <tt>cause</tt>). This constructor is useful for runtime exceptions
* that are little more than wrappers for other throwables.
*
* @param cause the cause (which is saved for later retrieval by the
* {@link #getCause()} method). (A <tt>null</tt> value is
* permitted, and indicates that the cause is nonexistent or
* unknown.)
* @since 1.4
*/
public RuntimeException(Throwable cause) {
super(cause);
} /**
* Constructs a new runtime exception with the specified detail
* message, cause, suppression enabled or disabled, and writable
* stack trace enabled or disabled.
*
* @param message the detail message.
* @param cause the cause. (A {@code null} value is permitted,
* and indicates that the cause is nonexistent or unknown.)
* @param enableSuppression whether or not suppression is enabled
* or disabled
* @param writableStackTrace whether or not the stack trace should
* be writable
*
* @since 1.7
*/
protected RuntimeException(String message, Throwable cause,
boolean enableSuppression,
boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
package com.todaytech.pwp.core.exception; public class SysException
extends RuntimeException
{
public SysException() {} public SysException(String message)
{
super(message);
} public SysException(String message, Throwable cause)
{
super(message, cause);
} public SysException(Throwable cause)
{
super(cause);
}
}
package com.todaytech.pwp.core.util.beanutils; import com.todaytech.pwp.core.exception.SysException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.DynaClass;
import org.apache.commons.beanutils.DynaProperty;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.beanutils.converters.BigDecimalConverter; public final class ReflectUtil
{
private ReflectUtil() {} public static String getFieldByName(Object orig, String fieldName, boolean pbIgnoreCase)
{
Field[] origFields = getDeclaredFieldsForClass(orig.getClass());
String fieldNameToFind = fieldName;
if (pbIgnoreCase) {
fieldNameToFind = fieldName.toUpperCase();
}
Object objValue = null; for (int i = 0; i < origFields.length; i++) {
Field origField = origFields[i];
String name = origField.getName();
if (pbIgnoreCase) {
name = name.toUpperCase();
}
if (name.equals(fieldNameToFind)) {
origField.setAccessible(true);
try {
objValue = origField.get(orig);
} catch (IllegalAccessException e) {
throw new SysException(e);
}
origField.setAccessible(false);
break;
}
}
if (objValue != null) {
return ConvertUtils.convert(objValue);
}
return null;
} public static void setFieldByName(Object orig, String fieldName, String value, boolean pbIgnoreCase)
{
Field[] origFields = getDeclaredFieldsForClass(orig.getClass());
String fieldNameToFind = fieldName;
if (pbIgnoreCase) {
fieldNameToFind = fieldName.toUpperCase();
}
boolean found = false; for (int i = 0; i < origFields.length; i++) {
Field origField = origFields[i];
String name = origField.getName();
if (pbIgnoreCase) {
name = name.toUpperCase();
}
if (name.equals(fieldNameToFind)) {
origField.setAccessible(true);
try {
origField.set(orig, value);
} catch (IllegalAccessException e) {
throw new SysException(e);
}
origField.setAccessible(false);
found = true;
break;
}
}
if (!found) {
throw new IllegalArgumentException("Field not found. fieldName ='" + fieldName + "'");
}
} public static Object invokeMethod(Object owner, String methodName, Object... args)
{
Class ownerClass = owner.getClass();
Class[] argsClass = new Class[args.length];
int i = 0; for (int j = args.length; i < j; i++) {
argsClass[i] = args[i].getClass();
}
Method method = null;
try {
method = ownerClass.getMethod(methodName, argsClass);
return method.invoke(owner, args);
} catch (NoSuchMethodException e) {
throw new SysException(e);
} catch (InvocationTargetException e) {
throw new SysException(e);
} catch (IllegalAccessException e) {
throw new SysException(e);
}
} public static Object invokeStaticMethod(String className, String methodName, Object... args)
{
Class ownerClass = null;
try {
ownerClass = Class.forName(className);
Class[] argsClass = new Class[args.length];
int i = 0; for (int j = args.length; i < j; i++) {
argsClass[i] = args[i].getClass();
}
Method method = ownerClass.getMethod(methodName, argsClass);
return method.invoke(null, args);
} catch (ClassNotFoundException e) {
throw new SysException(e);
} catch (InvocationTargetException e) {
throw new SysException(e);
} catch (NoSuchMethodException e) {
throw new SysException(e);
} catch (IllegalAccessException e) {
throw new SysException(e);
}
} public static Object newInstance(String className, Object... args)
{
Class newoneClass = null;
try {
newoneClass = Class.forName(className);
Class[] argsClass = new Class[args.length];
int i = 0; for (int j = args.length; i < j; i++) {
argsClass[i] = args[i].getClass();
}
Constructor cons = newoneClass.getConstructor(argsClass);
return cons.newInstance(args);
} catch (ClassNotFoundException e) {
throw new SysException(e);
} catch (InvocationTargetException e) {
throw new SysException(e);
} catch (NoSuchMethodException e) {
throw new SysException(e);
} catch (InstantiationException e) {
throw new SysException(e);
} catch (IllegalAccessException e) {
throw new SysException(e);
}
} public static void copyNotNullProperties(Object objFrom, Object objTo)
{
copyAllPropertiesByName(objFrom, objTo, false);
} public static void copyAllProperties(Object objFrom, Object objTo)
{
ConvertUtils.register(new DateConverter(), java.util.Date.class);
ConvertUtils.register(new DateConverter(), java.sql.Date.class);
ConvertUtils.register(new BigDecimalConverter(null), BigDecimal.class);
copyAllPropertiesByName(objFrom, objTo, true);
} private static void copyAllPropertiesByName(Object objFrom, Object objTo, boolean bIncludeNull)
{
if (bIncludeNull) {
try {
BeanUtils.copyProperties(objTo, objFrom);
} catch (IllegalAccessException e) {
throw new SysException(e);
} catch (InvocationTargetException e) {
throw new SysException(e);
}
} else {
copyProperties(objTo, objFrom, bIncludeNull);
}
} private static void copyProperties(Object dest, Object orig, boolean bIncludeNull)
{
if (dest == null) {
throw new IllegalArgumentException("No destination bean specified");
}
if (orig == null) {
throw new IllegalArgumentException("No origin bean specified");
} if ((orig instanceof DynaBean)) {
copyDynaBean(dest, (DynaBean)orig, bIncludeNull);
} else if ((orig instanceof Map)) {
copyBeanMap(dest, (Map)orig, bIncludeNull);
} else {
copyBeanArray(dest, orig, bIncludeNull);
}
} private static void copyBeanArray(Object dest, Object orig, boolean bIncludeNull) {
PropertyDescriptor[] origDescriptors = PropertyUtils.getPropertyDescriptors(orig);
for (int i = 0; i < origDescriptors.length; i++) {
String name = origDescriptors[i].getName();
if (!"class".equals(name))
{ if ((PropertyUtils.isReadable(orig, name)) && (PropertyUtils.isWriteable(dest, name)))
try {
Object value = PropertyUtils.getSimpleProperty(orig, name);
if ((bIncludeNull) || (value != null)) {
BeanUtils.copyProperty(dest, name, value);
}
} catch (NoSuchMethodException ex) {
throw new SysException(ex);
} catch (InvocationTargetException e) {
throw new SysException(e);
} catch (IllegalAccessException e) {
throw new SysException(e);
}
}
}
} private static void copyBeanMap(Object dest, Map orig, boolean bIncludeNull) {
Iterator names = orig.keySet().iterator();
while (names.hasNext()) {
String name = (String)names.next();
if (PropertyUtils.isWriteable(dest, name)) {
Object value = orig.get(name);
if ((bIncludeNull) || (value != null)) {
try {
BeanUtils.copyProperty(dest, name, value);
} catch (IllegalAccessException e) {
throw new SysException(e);
} catch (InvocationTargetException e) {
throw new SysException(e);
}
}
}
}
} private static void copyDynaBean(Object dest, DynaBean orig, boolean bIncludeNull) {
DynaProperty[] origDescriptors = orig.getDynaClass().getDynaProperties();
for (int i = 0; i < origDescriptors.length; i++) {
String name = origDescriptors[i].getName();
if (PropertyUtils.isWriteable(dest, name)) {
Object value = orig.get(name);
if ((bIncludeNull) || (value != null)) {
try {
BeanUtils.copyProperty(dest, name, value);
} catch (IllegalAccessException e) {
throw new SysException(e);
} catch (InvocationTargetException e) {
throw new SysException(e);
}
}
}
}
} public static void setPropertyByName(Object objTo, String sFieldName, Object value, boolean bIgnoreCase)
{
if (bIgnoreCase) {
sFieldName = findPropertyName(objTo.getClass(), sFieldName);
}
try {
BeanUtils.copyProperty(objTo, sFieldName, value);
} catch (IllegalAccessException e) {
throw new SysException(e);
} catch (InvocationTargetException e) {
throw new SysException(e);
}
} private static String findPropertyName(Class objClz, String sFieldName)
{
Field[] fields = getDeclaredFields(objClz);
String sToRet = null;
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
String fieldName = field.getName();
if (fieldName.equalsIgnoreCase(sFieldName)) {
sToRet = fieldName;
break;
}
}
return sToRet;
} private static Field[] getDeclaredFields(Class objClz)
{
ArrayList fields = new ArrayList();
Class curClz = objClz;
Collections.addAll(fields, curClz.getDeclaredFields());
while (curClz.getSuperclass() != Object.class) {
curClz = curClz.getSuperclass();
Collections.addAll(fields, curClz.getDeclaredFields());
}
return (Field[])fields.toArray(new Field[fields.size()]);
} private static Field[] getDeclaredFieldsForClass(Class clz)
{
if (clz == Object.class) {
return new Field[0];
}
ArrayList<Field> fieldlist = new ArrayList();
fieldlist.addAll(Arrays.asList(clz.getDeclaredFields()));
Field[] fieldsOfSuperClz = getDeclaredFieldsForClass(clz.getSuperclass());
if (fieldsOfSuperClz != null) {
fieldlist.addAll(Arrays.asList(fieldsOfSuperClz));
}
return (Field[])fieldlist.toArray(new Field[0]);
} private static Map<String, Object> describeByFields(Object obj, boolean bGetSuperClassToo)
{
if (obj == null) {
throw new IllegalArgumentException("No obj specified");
}
Class classToView = obj.getClass();
return describeByFields(obj, classToView, bGetSuperClassToo);
} private static Map<String, Object> describeByFields(Object obj, Class pClassToView, boolean bGetSuperClassToo)
{
Map<String, Object> toReturn = new HashMap();
if (bGetSuperClassToo) {
Class superclz = pClassToView.getSuperclass();
if (superclz != Object.class) {
toReturn.putAll(describeByFields(obj, superclz, bGetSuperClassToo));
}
}
Field[] origFields = pClassToView.getDeclaredFields();
for (Field origField : origFields) {
String name = origField.getName();
origField.setAccessible(true);
try {
toReturn.put(name, origField.get(obj));
} catch (IllegalAccessException e) {
throw new SysException(e);
}
}
return toReturn;
} public static <T> Class<T> getGenericTypeArgument(Class clazz)
{
return getGenericTypeArgument(clazz, 0);
} public static Class getGenericTypeArgument(Class clazz, int index)
{
Type genType = clazz.getGenericSuperclass(); if (!(genType instanceof ParameterizedType))
{
return Object.class;
} Type[] params = ((ParameterizedType)genType).getActualTypeArguments(); if ((index >= params.length) || (index < 0))
{ return Object.class;
}
if (!(params[index] instanceof Class))
{
return Object.class;
} return (Class)params[index];
}
}
Java对象之间的深度复制拷贝的更多相关文章
- JSON 与JAVA对象之间的转换(转)
JSON与XML两者目前在数据交互方面都有很高的使用率,随着现在SOA的兴起,异构系统的整合地位相应提高,本篇文章主要介绍JSON与JAVA对象之间的相互转换. 一.对普通类型的JSON模式的转换 一 ...
- 别名现象,java对象之间的相互赋值
请看一下代码 import java.util.*; class book{ static int c = null; } public static void main(String[] args ...
- json、xml和java对象之间的转化
其实从面相对象的角度来理解这个问题,就会很清晰.java中的一切皆对象即把世间万物(Everything in the world)看做java对象,任何处理不了的问题都可以先转化成java对象在做处 ...
- JAVA里面json和java对象之间的相互转换
1. 把java 对象列表转换为json对象数组,并转为字符串 JSONArray array = JSONArray.fromObject(list); String jsonstr = ar ...
- XML字符串和JAVA对象之间的转化
1.JAXB中相关的注解.类和接口说明 JAXB 中主要的一些注解 - shenyunsese 的专栏 - CSDN 博客 注:教程很全面很详细.但是仅供参考. 主要疑问区分和说明: 1.1 @X ...
- java 对象之间的复制
package com.jy.demo.web; import java.util.Date; public class People { private String name;//姓名 priva ...
- [No0000B9]C# 类型基础 值类型和引用类型 及其 对象复制 浅度复制vs深度复制 深入研究2
接上[No0000B5]C# 类型基础 值类型和引用类型 及其 对象判等 深入研究1 对象复制 有的时候,创建一个对象可能会非常耗时,比如对象需要从远程数据库中获取数据来填充,又或者创建对象需要读取硬 ...
- js对象/数组深度复制
今天碰到个问题,js对象.数组深度复制:之前有见过类似的,不过没有实现函数复制,今晚想了一下,实现代码如下: function clone(obj) { var a; if(obj instanceo ...
- JAVA对象和XML文档、原来他们之间还有这一出
最近项目开发中遇到一个问题,访问接口不再通过url地址请求的方式,而是 通过socket发送xml格式的报文到指定服务器来进行信息的统一认证.. 因此组装xml格式的报文字符串以及解析服务器返回的xm ...
随机推荐
- 隐马尔可夫模型HMM(一)
摘自 1.李航的<统计学习方法> 2.https://www.cnblogs.com/pinard/p/6945257.html 了解HMM模型 1.隐马尔可夫模型的定义 隐马尔可夫模型是 ...
- addEventListener() 和 removeEventListener()
addEventListener() 方法用于向指定元素添加事件句柄. 提示: 使用 removeEventListener() 方法来移除 addEventListener() 方法添加的事件句柄. ...
- mysql 案例 ~ 表空间迁移数据与数据导入
一 简介:mysql5.6+的表空间传输二 目的:复制数据到另一个表三 步骤 1 create table b like a ->创建一个空表 2 alter table b disc ...
- mybatis 三剑客 generator配置 、mybatis plugin
generator配置 1.配置pom.xml 导入mysql驱动.mybatis.mybatis-generator的依赖 <dependency> <groupId>org ...
- ffmpeg笔记
1.视频降低质量,减小体积: ffmpeg -i aaa.mp4 -strict -2 -qscale 20 -y outfile.mp4
- HBSX2019 3月训练
Day 1 3月有31天废话 今天先颓过了就只剩30天了 初步计划 每天一道字符串/数据结构题 图论学习 根据<若干图论模型探讨>(lyd)复习 二分图与网络流学习 <算法竞赛进阶指 ...
- 修改Spring Social默认提交地址
⒈ package cn.coreqi.social.config; import org.springframework.social.security.SocialAuthenticationFi ...
- 10分钟搭建Kubernetes容器集群平台【转】
官方提供3种方式部署Kubernetes minikube Minikube是一个工具,可以在本地快速运行一个单点的Kubernetes,尝试Kubernetes或日常开发的用户使用.不能用于生产环境 ...
- vue之递归组件实现树形目录
递归组件的应用===>可以通过组件命名来自己使用自己的组件 实例如下 父组件 <div class="content"> <detail-list :lis ...
- 结构数组新发现之直接初始化《leetcode-合并区间》
leetcode有时候会要求一些奇怪(陌生)的数据形式,刷题因为数据形式卡住了真的很不好... 合并区间里定义了一个Interval的结构数组 struct Interval { int start; ...