Search code examples
javaannotations

Is there a Java wrapper annotation?


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.


Solution

  • 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;
    
    }