Java itself provides the ability to replicate objects, There is a clone method in the Java.lang.Object class, which is a protected method in which the subclass needs to override this method and declare it as a public type, and also implement the Cloneable interface to provide the ability to replicate objects, clone () is a native method, the efficiency of the native method is generally much higher than the native method in Java, the performance is more concerned about the first consideration of this way, this replication on the Internet there are many examples are not much written; another way to do this-- Copying objects through a Java reflection mechanism is likely to be less efficient than clone () and does not support deep replication and replication of collection types, but the commonality is much higher, with the following code for copying:
Copy Code code as follows:
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 ("Set Parameter information occurrence exception", e);
}
return Targetbean;
}
This method receives two parameters, one is the copied source object-the object to be copied, one is the copied target object-the object copy, of course, this method can also be used between two different objects, so long as the target object and object have one or more attributes of the same type and name. The property value of the source object is then assigned to the target object's properties.