I need to create a proxy for a class. I do not have access to the concrete subject but only to the subject interface. I have also a factory method to create the instance of the original implementation.
If I use Eclipse I can get a stub for each method:
@Override
public R1 method(T1 p1) {
// TODO Auto-generated method stub
return null;
}
I need to create implementation like this:
@Override
public R1 method(T1 p1) {
return instance.method(p1);
}
Because there are a lot of methods I used regexp with search and replace. Search for:
public ([a-z,A-Z,\.]*) ([a-z,A-Z]*)\(([a-z,A-Z]* ([a-z,A-Z]*))?\) \{\r\n([ ,\t]*)// TODO Auto-generated method stub\r\n[ ,\t]*return [0-9,a-z,A-Z]*\;
And replace with:
public \1 \2\(\3\) \{\r\n\5return instance\.\2\(\4\);
Is there a better solution?
Another problem comes with methods that take more params:
@Override
public R1 method(T1 p1, T2 p2) {
// TODO Auto-generated method stub
return null;
}
The only solution I found is to have a different search-replace pairs for each number of params. Is there a better solution?
The easisest solution would probably to just use and IDE. For example in Netbeans 7 you could write the following skeleton:
Then you place your curson inside the class, hit
ALTandInsert, choose “delegate method”, select all methods of the interface and click on generate.Another, more dynamic, possibility would be to use the java.lang.reflect.Proxy class of the jdk. This allows you to define a class at runtime that implements a given interface: