1 package spoon.support.visitor; 2 3 import java.lang.reflect.Field ; 4 import java.util.Collection ; 5 import java.util.List ; 6 7 import spoon.processing.FactoryAccessor; 8 import spoon.reflect.declaration.CtElement; 9 import spoon.reflect.reference.CtReference; 10 import spoon.reflect.visitor.CtScanner; 11 import spoon.support.util.RtHelper; 12 13 17 public class ElementReplacer<T extends FactoryAccessor> extends CtScanner { 18 19 T replacement; 20 21 T toReplace; 22 23 29 public ElementReplacer(T toReplace, T replacement) { 30 super(); 31 this.replacement = replacement; 32 this.toReplace = toReplace; 33 } 34 35 private T getReplacement(Object parent) { 36 T ret = replacement.getFactory().Core().clone(replacement); 37 if (ret instanceof CtElement && parent instanceof CtElement) { 38 ((CtElement) ret).setParent((CtElement) parent); 39 } 40 return ret; 41 } 42 43 @SuppressWarnings ("unchecked") 44 private void replaceIn(Object parent) throws Exception { 45 46 48 58 for (Field f : RtHelper.getAllFields(parent.getClass())) { 60 f.setAccessible(true); 61 Object tmp = f.get(parent); 62 63 if (tmp != null) { 64 if (tmp instanceof List ) { 65 List <T> lst = (List <T>) tmp; 66 67 for (int i = 0; i < lst.size(); i++) { 68 if (lst.get(i)!=null && lst.get(i).equals(toReplace)) { 69 lst.remove(i); 70 if(replacement!=null) 71 lst.add(i, getReplacement(parent)); 72 } 73 } 74 } else if (tmp instanceof Collection ) { 75 Collection <T> collect = (Collection <T>) tmp; 76 Object [] array = collect.toArray(); 77 for (Object obj : array) { 78 if (obj.equals(toReplace)) { 79 collect.remove(obj); 80 collect.add(getReplacement(parent)); 81 } 82 } 83 } else if (tmp.equals(toReplace)) { 84 f.set(parent, getReplacement(parent)); 85 } 86 } 87 } 88 } 89 90 93 @Override 94 public void enter(CtElement e) { 95 try { 96 replaceIn(e); 97 } catch (Exception e1) { 98 e1.printStackTrace(); 99 } 100 super.enter(e); 101 } 102 103 106 @Override 107 public void enterReference(CtReference e) { 108 try { 109 replaceIn(e); 110 } catch (Exception e1) { 111 e1.printStackTrace(); 112 } 113 super.enterReference(e); 114 } 115 116 } 117 | Popular Tags |