【问题标题】:How to use lombok's @Delegate annotations in Java如何在 Java 中使用 lombok 的 @Delegate 注解
【发布时间】:2020-06-18 02:06:41
【问题描述】:

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

【问题讨论】:

    标签: java annotations lombok


    【解决方案1】:

    来自龙目岛documentation

    要非常精确地控制委托和不委托的内容,请编写带有方法签名的私有内部接口,然后将这些私有内部接口指定为类型

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

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

    private interface Exclude {
        int getAge();
    }
    

    并将其传递给exclude:

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

    【讨论】:

      猜你喜欢
      • 2020-05-16
      • 2019-06-15
      • 1970-01-01
      • 2014-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多