ute the original method. } }; f.setFilter(new MethodFilter() { public boolean isHandled(Method m) { // ignore finalize() return !m.getName().equals("finalize"); } }); Class c = f.createClass(); Foo foo = (Foo)c.newInstance(); ((ProxyObject)foo).setHandler(mi);
Then, the following method call will be forwarded to MethodHandler mi
and prints a message before executing the originally called method bar()
in Foo
.
foo.bar();
The last three lines of the code shown above can be replaced with a call to the helper method create
, which generates a proxy class, instantiates it, and sets the method handler of the instance:
: Foo foo = (Foo)f.create(new Class[0], new Object[0], mi);
To change the method handler during runtime, execute the following code:
MethodHandler mi2 = ... ; // another handler ((ProxyObject)foo).setHandler(mi2);
You can also specify the default method handler:
ProxyFactory f2 = new ProxyFactory(); f2.setSuperclass(Foo.class); f2.setHandler(mi); // set the default handler Class c2 = f2.createClass();
The default handler is implicitly attached to an instance of the generated class c2
. Calling setHandler
on the instance is not necessary unless another method handler must be attached to the instance.
The following code is an example of method handler. It does not execute anything except invoking the original method:
class SimpleHandler implements MethodHandler { public Object invoke(Object self, Method m, Method proceed, Object[] args) throws Exception { return proceed.invoke(self, args); } }
A proxy object generated by ProxyFactory
is serializable if its super class or interfaces implement a java.io.Serializable
. However, a serialized proxy object will not be compatible with future releases. The serialization support should be used for short-term storage or RMI.
@see MethodHandler
@since 3.1