Java provides the ability to copy objects. lang. there is a clone method in the Object class. This method is a protected method. In the subclass, you must override this method and declare it as the public type. In addition, you must implement the Cloneable interface to provide Object replication capabilities, clone () is a native method. The efficiency of native methods is generally much higher than that of non-native methods in java. If you are concerned about performance, consider this method first, there are a lot of examples on the Internet for this replication, so I won't write more; another method to use here -- copying objects through the java reflection mechanism, this method may be less efficient than clone, in addition, deep replication and replica set types are not supported, but the versatility will be improved a lot,Below is the copy code:
Copy codeThe Code is 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 ("Setting Parameter information Exception", e );
}
Return TargetBean;
}
This method receives two parameters. One is the copied source object-the object to be copied, and the other is the copied target object-the object copy. Of course, this method can also be used between two different objects, at this time, as long as the target object and the object have one or more attributes of the same type and name, the attribute value of the source object will be assigned to the attribute of the target object.