Is there a way to autogenerate wrappers in Eclipse?
Asked Answered
P

3

22

I have to create several proxies, to add, for example, logging. Something like that:

interface IMath {
    public int add(a, b);
}

class Math implements IMath {
    public int add(a, b) { return a + b; }
}

class MathWithLogs implements IMath {
    private IMath realMath;
    public int add(a, b) {
        Log.d("tag", "valueable info");
        return realMath.add(a, b);
    }
}

Everything is fine as long as these interfaces aren't 20 methods and I have to add something to just one.

My question is, is there a way to autogenerate wrapper classes with some plugin for eclipse?

Or maybe there is a way to do something with annotations to invoke methods from realMath unless stated otherwise (like @Override)?

Paediatrics answered 17/8, 2012 at 10:19 Comment(1)
You might also want to look at AspectJ (or generally speaking, AOP), and also Java's standard Proxy mechanisms. These would gracefully handle your use-case above without requiring any new class being written.Predacious
R
30

Right click in any source file (.java) and navigate to source -> Override/Implement Methods/Generate Delegate Methods.

The first will paste the body of all methods of your immediate interface. the second will do the same for all the hierarchy up to Object(I guess, not sure). Hope this helps.

Resuscitator answered 17/8, 2012 at 10:29 Comment(1)
Either of them support all the hierarchy up to Object. Only the delegate one supports delegates which are usually what you want in a wrapper class. And for that one, you can't just right-click anywhere in a source file, you have to right-click on the field which you want to delegate to.Aboveboard
S
11

Yes, there is a source generator called "Generate Delegate Methods" which will do exactly what you want.

Susiesuslik answered 17/8, 2012 at 10:22 Comment(0)
A
11

It took me a while after reading the other answers to work out exactly what to do. The solution is:

  1. Create your (initially empty) wrapper class which implements the required interface. Make sure to uncheck "Inherited abstract methods" when creating the class.
  2. Inside your new wrapper class (which will show an error at the moment due to the fact that it lacks the interface implementations), create a field which has type equal to the required interface.
  3. Right click the field you just created and select Source -> Generate Delegate Methods.
  4. Check the methods you want to create and click OK.
  5. Finally, add a single-arg constructor or a setter method for the field (it's not automatically generated as part of this process).
Aboveboard answered 19/5, 2015 at 21:19 Comment(1)
This answer is worth recalling SO credentials and logging in just to upvote/ Thanks!Confer

© 2022 - 2024 — McMap. All rights reserved.