Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I don't know how applicable this is to your situation but the best way to intercept method calls is by using dynamic proxies. For this you have to create interfaces for your classes though, which you might have done anyway.</p> <p>Here's an example of how dynamic proxies work:</p> <pre><code> interface Foo { void setBar( String bar ); String getBar(); } class FooImpl implements Foo { private String bar; // getter and setter } </code></pre> <p>This is your normal code. Now what you can do is instead of <code>new FooImpl()</code> you can use a proxy. For the proxy you need an [<code>InvocationHandler][1]</code> first.</p> <pre><code> class LockHandler implements InvocationHandler { private FooImpl originalOb; public LockHandler( FooImpl originalOb ) { this.originalOb = originalOb; } @Override public Object invoke( Object proxy, Method method, Object [] args ) { try { if( method.getName().startsWith( "set" ) { // do locking stuff } return method.invoke( originalOb, args ); //invoke underlying method } finally { if( method.getName().startsWith( "set" ) { // do post-call locking stuff } } } } </code></pre> <p>And then you finally create your <a href="http://download.oracle.com/javase/6/docs/api/java/lang/reflect/Proxy.html#Proxy%28java.lang.reflect.InvocationHandler%29" rel="nofollow"><code>Proxy</code></a> object:</p> <pre><code> Foo foo = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(), new Class[] { Foo.class }, new LockHandler( new FooImpl() ) ); </code></pre> <p>Now every call to your <code>foo</code> object will be channeled into your invocation handler. Of course you don't have to create a new invocation handler instance for every object, you don't even need a separate one for every interface, <code>originalOb</code> could (and in real life should) be declared as <code>Object</code> type. </p> <p>Another option is to use an aspect implementation, like AspectJ, which is probably simpler to use but it may be too late to introduce it, depending on how far you're into the development of the software.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload