Java中如何使用lombok的@Delegate注解

How to use lombok's @Delegate annotations in Java

我想在我的代码中使用 lombok 的 @Delegate 注释。 请检查下面的代码片段,它会抛出一条错误消息: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();
    }
}

来自龙目岛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).

这意味着要包含 I 中的所有内容,但仅排除 getAge,您可以像这样声明一个额外的内部接口:

private interface Exclude {
    int getAge();
}

并将其传递给 exclude:

@Delegate(types = I.class, excludes = Exclude.class)