オーバーライドされたメソッドの元のメソッドを呼び出してみた。
ネタ元
http://d.hatena.ne.jp/cero-t/20080815/1218812380
CGLIB使ったほうが楽そうだったのでこっちでやってみた。
当然、ASMは必要です。
ソースはこんな感じ。
これでBaseクラスのメソッドが呼ばれます。
package test; import java.lang.reflect.Method; import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodProxy; /** * * @author kensir0u */ public class SuperMethodInterceptor implements MethodInterceptor { public Object intercept(Object o, Method m, Object[] args, MethodProxy mp ) throws Throwable { try { return mp.invokeSuper(o, args); } catch(Throwable t) { throw t; } } }
package test; import net.sf.cglib.proxy.Enhancer; class Base{ public int aMethod() { System.out.println("Base#aMethod called."); return 1; } } /** * * @author kensir0u */ public class Main extends Base{ /** * @param args the command line arguments */ public static void main(String[] args) { Base b = createProxy(Main.class); b.aMethod(); } public int aMethod() { System.out.println("Main#aMethod called."); return 1; } public static <T> T createProxy(Class clazz) { Enhancer e = new Enhancer(); e.setSuperclass(clazz.getSuperclass()); e.setCallback(new SuperMethodInterceptor()); return (T)e.create(); } }