3

Trying to find a way to wraps an object, which is auto generated based on some model with lots of getters and setters. For example:

class ObjectToWrap {

    public int getIntA();

    public int getIntB();

    ... // Tons of other getters
}

I have to create a wrapper that wraps this object and use some annotation that generates methods from ObjectToWrap for me. Code looks like the following:

class Wrapper {
    private ObjectToWrap obj;

    public int getIntA() {
        return obj.getIntA();
    }

    public int getIntB() {
        return obj.getIntB();
    }

    ... // Tons of other getters
}

Is there an annotation to do this? I just don't want to make the code look lengthy.

bohanl
  • 1,885
  • 4
  • 17
  • 33
  • 3
    Duplicate of http://stackoverflow.com/q/13348215/1686330 Btw., what you are trying to achive is to auto create delegate methods: https://www.princeton.edu/~achaney/tmve/wiki100k/docs/Delegation_pattern.html – Dirk Lachowski Aug 08 '14 at 09:01
  • @Zhuinden, what exact annotation were you referring to? – bohanl Aug 08 '14 at 09:06
  • 2
    That is called delegating, and when those generated classes were interfaces go for @DirkLachowski's link, dynamic proxies. – Joop Eggen Aug 08 '14 at 09:08

2 Answers2

6

Take a look at Project Lombok which has a @Delegate annotation which does exactly what you want.

@Delegate documentation

I think you would be able to do this:

import lombok.Delegate;
class Wrapper {
    //the types field in the annotation says
    //to only auto generate deleagate methods
    //for only the public methods in the ObjectToWrap class
    //and not any parent classes if ObjectToWrap extended something 
    @Delegate(types = ObjectToWrap.class)
    private ObjectToWrap obj;

}
dkatzel
  • 31,188
  • 3
  • 63
  • 67
1

If you are using the maven build infrastructure with dependency management, you could have a dependent sub-project that collects the generated sources as-is (not as code). Another sub-project could then generate real sources out of them (source code transformation) as zip, which then could be imported by maven in the main project as pre-compile target.

On that basis you could use dynamic proxy classes, or even immediate generated classes.


The only other alternative would be to use the java scripting API, and do the business in JavaScript or so. Loosing the type safeness of java and lowering the software quality.

Unfortunately the alternative of hybrid usage of another JVM language I cannot consider productive. The very nice and powerful Scala still is too wild/complex/ticklish.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138