In depth analysis of Java object replication

  • 2020-04-01 01:58:35
  • OfStack

Java itself provides the ability of Object replication, in Java. Lang. Object class in the clone method, this method is a protected method and declared to public in subclasses need to rewrite this method and type, but also need to implement Cloneable interface can provide the ability of Object replication, clone () is a native method, the efficiency of the native methods in general are much higher than the native methods in Java, the performance is concerned first consider this way, There are many examples of this kind of copying on the Internet, but not many; Another way to use it here is to copy objects through Java's reflection mechanism, which is probably less efficient than clone() and does not support deep replication or replication of collection types, but is much more common. Here's the copy code:


private <T> T getBean(T TargetBean, T SourceBean) {
        if (TargetBean== null) return null;
        Field[] tFields = TargetBean.getClass().getDeclaredFields();
        Field[] sFields = SourceBean.getClass().getDeclaredFields();
        try {
            for (Field field : tFields ) {
                String fieldName = field.getName();
                if (fieldName.equals("serialVersionUID")) continue;
                if (field.getType() == Map.class) continue;
                if (field.getType() == Set.class) continue;
                if (field.getType() == List.class) continue;
                for (Field sField : sFields) {
                    if(!sField .getName().equals(fieldName)){
                        continue;
                    }
                    Class type = field.getType();
                    String setName = getSetMethodName(fieldName);
                    Method tMethod = TargetBean.getClass().getMethod(setName, new Class[]{type});
                    String getName = getGetMethodName(fieldName);
                    Method sMethod = SourceBean.getClass().getMethod(getName, null);
                    Object setterValue = voMethod.invoke(SourceBean, null);
                    tMethod.invoke(TargetBean, new Object[]{setterValue});
                }
            }
        } catch (Exception e) {
            throw new Exception(" The setting parameter information is abnormal ", e);
        }
        return TargetBean;
}

The method takes two parameters, is a copy of the source object - to copy the object, one is a copy of the target object - a copy of the object, of course, this method can also be used between two different objects, this time as long as the target object and object has one or more of the same type and the name of the attribute, so will the source object is assigned to the attribute value of the target object properties.


Related articles: