Scenario: Converting a hierarchical class object (domain-driven model object) to a tiled class object (view)
src object, (red box is sub-object)
Target object (Tiled object)
Code idea, recursive reflection traversal all fields, stored in a map, and then recursively assigned to the target object
Defect: A field with the same name between different sub-objects is overwritten with a value
Code
Private Static voidGetsrcallfieldmap (Object obj,map<string,object>Collectmap) {Class Srcclazz=Obj.getclass (); Field[] Srcfields=Srcclazz.getdeclaredfields (); Stream.of (Srcfields). ForEach (Field-{field.setaccessible (true); Try { if(Field.gettype (). ToString (). Contains ("Aacoin.account") &&!Field.gettype (). Isenum ()) {Object Subobj=field.get (obj); if(subobj!=NULL) Getsrcallfieldmap (SUBOBJ,COLLECTMAP); }Else{collectmap.put (Field.getname (), Field.get (obj)); } } Catch(illegalaccessexception e) {e.printstacktrace (); } }); } Private Static voidSettargetallfield (Object obj, map<string,object>Srcmap) {Class Srcclazz=Obj.getclass (); Field[] Srcfields=Srcclazz.getdeclaredfields (); Stream.of (Srcfields). ForEach (Field-{field.setaccessible (true); Try { if(Field.gettype (). ToString (). Contains ("AACOIN.TRADE.OTC") &&!Field.gettype (). Isenum ()) {Object Subobj=field.get (obj); if(Subobj = =NULL) {Constructor cons= Field.gettype (). Getdeclaredconstructor (NULL); Cons.setaccessible (true); Subobj= Cons.newinstance (NULL); Field.set (obj, subobj); } Settargetallfield (Subobj, Srcmap); }Else{ //Collectmap.put (field,obj);Object Currentfield =Srcmap.get (Field.getname ()); if(Currentfield! =NULL&& Field.gettype () = =Currentfield.getclass ()) {Field.set (Obj,currentfield); } } } Catch(illegalaccessexception e) {e.printstacktrace (); } Catch(instantiationexception e) {e.printstacktrace (); } Catch(nosuchmethodexception e) {e.printstacktrace (); } Catch(InvocationTargetException e) {e.printstacktrace (); } }); } Public Static<T> T Convert (Object src,class<t>Tclass) {Constructor<T> cons =NULL; Try{Cons= Tclass.getdeclaredconstructor (NULL); } Catch(nosuchmethodexception e) {e.printstacktrace (); } cons.setaccessible (true); T result=NULL; Try{result= Cons.newinstance (NULL); } Catch(instantiationexception e) {e.printstacktrace (); } Catch(illegalaccessexception e) {e.printstacktrace (); } Catch(InvocationTargetException e) {e.printstacktrace (); } convert (Src,result); returnresult; } Public Static<T>T Convert (Object src,t result) {Map<String,Object> Srcmap =NewHashMap (); Getsrcallfieldmap (SRC,SRCMAP); Settargetallfield (RESULT,SRCMAP); returnresult; }
Call:
Advervo =convert (Advert,advertvo.class);
Write the more casual, directly swallowed the exception, need to handle, the exception of the uniform specification thrown
Java one object is assigned to another object, which supports the mutual transfer between the tiled class and the hierarchical class.