1 18 19 package org.objectweb.jac.core; 20 21 import java.lang.reflect.Modifier ; 22 import java.util.Collection ; 23 import java.util.Iterator ; 24 import org.apache.log4j.Logger; 25 import org.objectweb.jac.core.rtti.ClassItem; 26 import org.objectweb.jac.core.rtti.ClassRepository; 27 import org.objectweb.jac.core.rtti.CollectionItem; 28 import org.objectweb.jac.core.rtti.FieldItem; 29 import org.objectweb.jac.core.rtti.MethodItem; 30 import org.objectweb.jac.core.rtti.NoSuchMethodException; 31 import org.objectweb.jac.core.rtti.RttiAC; 32 import org.objectweb.jac.util.ExtArrays; 33 34 public class Utils { 35 static Logger logger = Logger.getLogger("clone"); 36 37 45 public static Object clone(Object o) 46 throws InstantiationException , IllegalAccessException , Exception 47 { 48 return clone(o,(FieldItem)null); 49 } 50 51 64 public static Object clone(Object o, FieldItem ignoredRelation) 65 throws InstantiationException , IllegalAccessException , Exception 66 { 67 logger.debug("Cloning "+o); 68 ClassRepository cr = ClassRepository.get(); 69 ClassItem cli = cr.getClass(o); 70 Object clone = cli.newInstance(); 71 Iterator i = cli.getAllFields().iterator(); 72 while (i.hasNext()) { 73 FieldItem field = (FieldItem)i.next(); 74 if (field.isCalculated() || ignoredRelation==field) 75 continue; 76 if (field.isPrimitive()) { 77 logger.debug(" copying value of fied "+field.getName()); 78 try { 79 Object fieldValue = field.getThroughAccessor(o); 80 81 try { 83 MethodItem mClone = cr.getClass(fieldValue).getMethod("clone()"); 84 if (mClone!=null && Modifier.isPublic(mClone.getModifiers())) 85 fieldValue = mClone.invoke(fieldValue, ExtArrays.emptyObjectArray); 86 } catch(NoSuchMethodException e) { 87 } 88 field.setThroughWriter(clone,fieldValue); 89 } catch (Exception e) { 90 logger.error("clone("+o+"): failed to clone field "+field,e); 91 } 92 } else if (field instanceof CollectionItem) { 93 CollectionItem collection = (CollectionItem)field; 94 logger.debug(" copying collection "+field.getName()); 95 if (collection.isMap()) { 96 } else { 97 Iterator j = ((Collection )collection.getThroughAccessor(o)).iterator(); 98 while(j.hasNext()) { 99 Object item = j.next(); 100 if (collection.isAggregation()) { 101 item = clone(item,(FieldItem)field.getAttribute(RttiAC.OPPOSITE_ROLE)); 102 } 103 collection.addThroughAdder(clone,item); 104 } 105 } 106 } else { 107 field.setThroughWriter(clone,field.getThroughAccessor(o)); 108 } 109 } 110 logger.debug(o+" cloned"); 111 return clone; 112 } 113 114 public static Object clone(Object o, String ignoredRelation) 115 throws InstantiationException , IllegalAccessException , Exception 116 { 117 return clone(o,ClassRepository.get().getClass(o).getField(ignoredRelation)); 118 } 119 } 120 | Popular Tags |