/*** Copy Object Properties (object type must be the same) * *@paramOrig Resource Object *@paramdest Target Object *@paramClazz Source Object class *@paramignorenull whether NULL is ignored (true: ignored, false: not ignored) *@return */ Public Static<T> t Copyproperties (t orig, T dest, Class<?> Clazz,Booleanignorenull) { if(Orig = =NULL|| Dest = =NULL) return NULL; if(!Clazz.isassignablefrom (Orig.getclass ()))return NULL; Field[] Fields=Clazz.getdeclaredfields (); for(Field field:fields) {Try{field.setaccessible (true); Object value=Field.get (orig); if(!java.lang.reflect.Modifier.isFinal (Field.getmodifiers ())) { if(! (ignorenull && Value = =NULL) {field.set (dest, value); }} field.setaccessible (false); } Catch(Exception e) {}}if(Clazz.getsuperclass () = = Object.class){ returndest; } returncopyproperties (orig, dest, Clazz.getsuperclass (), ignorenull); } /*** Copy Object Properties (object type must be the same) *@paramOrig Resource Object *@paramdest Target Object *@paramignorenull whether NULL is ignored (true: ignored, false: not ignored)*/ Public Static<T> t Copyproperties (t orig, T dest,Booleanignorenull) { if(Orig = =NULL|| Dest = =NULL) return NULL; returncopyproperties (orig, dest, Orig.getclass (), ignorenull); } /*** Copy objects *@paramsrc Resource Object *@returnNew Object*/@SuppressWarnings ("Unchecked") Public Static<T>t Clone (t src) {if(src = =NULL){ return NULL; } T NewObject=NULL; Try{newObject=(T) Src.getclass (). newinstance (); } Catch(Exception e) {e.printstacktrace (); } returnCopyproperties (SRC, newObject,false); }
Java Copy object and copy object properties