You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

JBPAPP9257Test.java 2.5KB

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