1 package test.javassist.proxy; 2 3 import java.lang.reflect.Method; 4 import javassist.util.proxy.ProxyFactory; 5 import javassist.util.proxy.MethodHandler; 6 import javassist.util.proxy.MethodFilter; 7 import javassist.util.proxy.ProxyObject; 8 import javassist.util.proxy.Proxy; 9 import junit.framework.TestCase; 10 11 @SuppressWarnings({"rawtypes","unchecked"}) 12 public class JBPAPP9257Test extends TestCase { testGetHandler()13 public void testGetHandler() throws Exception { 14 ProxyFactory f = new ProxyFactory(); 15 f.setSuperclass(Foo.class); 16 f.setFilter(new MethodFilter() { 17 public boolean isHandled(Method m) { 18 // ignore finalize() 19 return !m.getName().equals("finalize"); 20 } 21 }); 22 Class c = f.createClass(); 23 MethodHandler mi = new MethodHandler() { 24 public Object invoke(Object self, Method m, Method proceed, 25 Object[] args) throws Throwable { 26 System.out.println("Name: " + m.getName()); 27 return proceed.invoke(self, args) + "!"; // execute the original 28 // method. 29 } 30 }; 31 Foo foo = (Foo)c.getConstructor().newInstance(); 32 try { 33 ((ProxyObject)foo).setHandler(mi); 34 fail("foo is a ProxyObject!"); 35 } catch (ClassCastException e) {} 36 ((Proxy)foo).setHandler(mi); 37 assertEquals("I'm doing something!", foo.doSomething()); 38 assertEquals("This is a secret handler!", foo.getHandler()); 39 } 40 testGetHandler2()41 public void testGetHandler2() throws Exception { 42 ProxyFactory f = new ProxyFactory(); 43 f.setSuperclass(Foo2.class); 44 f.setFilter(new MethodFilter() { 45 public boolean isHandled(Method m) { 46 // ignore finalize() 47 return !m.getName().equals("finalize"); 48 } 49 }); 50 Class c = f.createClass(); 51 MethodHandler mi = new MethodHandler() { 52 public Object invoke(Object self, Method m, Method proceed, 53 Object[] args) throws Throwable { 54 System.out.println("Name: " + m.getName()); 55 return proceed.invoke(self, args) + "!"; // execute the original 56 // method. 57 } 58 }; 59 Foo2 foo = (Foo2)c.getConstructor().newInstance(); 60 try { 61 ((ProxyObject)foo).setHandler(mi); 62 fail("foo is a ProxyObject!"); 63 } catch (ClassCastException e) {} 64 ((Proxy)foo).setHandler(mi); 65 assertEquals("do something!", foo.doSomething()); 66 assertEquals("return a string!", foo.getHandler()); 67 } 68 } 69