1 package test; 2 3 import java.lang.reflect.InvocationTargetException ; 4 import java.lang.reflect.Method ; 5 import alt.jiapi.*; 6 import alt.jiapi.reflect.Loader; 7 import alt.jiapi.instrumentor.*; 8 import alt.jiapi.util.InstrumentingClassLoader; 9 10 16 public class MethodCallTest implements Hook { 17 private Class clazz; 18 private static Object instance; 19 private boolean callStatic; 20 21 public static void main(String [] args) throws Exception { 22 MethodCallTest mct = new MethodCallTest(args.length == 0); 23 mct.run(args); 24 } 25 26 public MethodCallTest(boolean callStatic) throws Exception { 27 this.callStatic = callStatic; 28 29 String className = System.getProperty("class", "test.Foo"); 30 System.out.println("Loading class " + className); 31 InstrumentationContext ctx = new InstrumentationContext(); 32 Instrumentor dispatcher = new MethodDispatcherInstrumentor(); 33 Instrumentor mei = new GrepInstrumentor(new MethodReturnStrategy()); 34 Instrumentor mcp = new MethodCallInstrumentor(this); 36 37 InstrumentorChain chain = new InstrumentorChain(); 38 chain.add(dispatcher); 39 chain.add(mei); 40 chain.add(mcp); 41 42 InstrumentationDescriptor id = new InstrumentationDescriptor(); 43 id.addInclusionRule("test.*"); 44 45 id.addExclusionRule("test.MethodCallTest"); 49 id.addChain(chain); 50 51 ctx.addInstrumentationDescriptor(id); 52 Loader loader = ctx.getLoader(); 53 ClassLoader cl = InstrumentingClassLoader.createClassLoader(ctx); 54 55 this.clazz = cl.loadClass(className); 56 } 57 58 public void callMeDynamic(String s1, String s2) { 59 System.out.println ("callMeDynamic : " + s1 + ", " + s2); 60 } 61 62 public static void callMeStatic(String s1, String s2) { 63 System.out.println ("callMeStatic : " + s1 + ", " + s2); 64 } 65 66 67 public Method getHookMethod() { 69 Method hookMethod = null; 70 Class [] params = new Class [] {String .class, String .class}; 71 72 if (callStatic) { 73 System.out.println("Instrumenting for static calls"); 74 try { 75 hookMethod = 76 this.getClass().getMethod("callMeStatic", params); 77 } 78 catch(Exception e) { 79 throw new RuntimeException (e.toString ()); 81 } 82 } 83 else { 84 System.out.println("Instrumenting for dynamic calls"); 85 try { 86 hookMethod = 87 this.getClass().getMethod("callMeDynamic", params); 88 } 89 catch(Exception e) { 90 throw new RuntimeException (e.toString ()); 92 } 93 } 94 95 return hookMethod; 96 } 97 98 99 public void run(String [] args) throws Exception { 100 java.lang.reflect.Method m = 101 clazz.getMethod("main", new Class [] {String [].class}); 102 103 try { 104 m.invoke(clazz, new Object [] {args}); 105 } catch (InvocationTargetException ite) { 106 System.err.println("Target exception:"); 107 ite.printStackTrace(); 108 if (ite.getTargetException() != null) { 109 ite.getTargetException().printStackTrace(); 110 } 111 } 112 } 113 114 public Object getInstance() { 115 return this; 116 } 117 } 118 | Popular Tags |