Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use lombok's @Delegate annotations in Java

I would like to use lombok's @Delegate annotations in the my code. Please check code snippet below and it throws an error saying :getAge() is already defined :

public interface I {
    String getName();
    int getAge();
}

@Data
public class Vo {
    private String name;
    private long age;
}

@AllArgsConstructor
public class Adapter implements I {

    @Delegate(types = I.class)
    private Vo vo;

    //I want to use my own code here,Because vo.getAge() returns a long,But I.getAge() expects a int
    public int getAge(){
        return (int) vo.getAge();
    }
}
like image 717
Tianchao Hongyu Avatar asked Apr 20 '26 15:04

Tianchao Hongyu


1 Answers

From the lombok documentation:

To have very precise control over what is delegated and what isn't, write private inner interfaces with method signatures, then specify these private inner interfaces as types in

@Delegate(types=PrivateInnerInterfaceWithIncludesList.class, excludes=SameForExcludes.class).

Which means that to include everything in I, but exclude only getAge, you can declare an extra inner interface like this:

private interface Exclude {
    int getAge();
}

and pass it to exclude:

@Delegate(types = I.class, excludes = Exclude.class)
like image 127
Sweeper Avatar answered Apr 23 '26 05:04

Sweeper