【问题标题】:Annotations passed strangely from the Immutables interface to the implementation注释从 Immutables 接口奇怪地传递到实现
【发布时间】:2018-03-11 10:54:22
【问题描述】:

我正在使用 Immutables 为这个接口生成不可变对象:

import javax.validation.constraints.Size;
...

@Value.Immutable
public interface Entity {
    @Size(max = 10) // removing this also works
    String name();
} 

但是生成的类字段对我来说看起来很奇怪:

private final java.lang.@Size(max = 10) String name;

请参阅@Size 注释前缀的java.lang. 垃圾。 有了它 - 验证不会按预期工作。

手动删除 - 一切正常。 这种行为的原因可能是什么? 检查 2.5.4-2.5.6 版本

【问题讨论】:

    标签: java bean-validation hibernate-validator annotation-processing immutables-library


    【解决方案1】:

    自创建问题 2 年多以来,我还是会回复,因为如果他们在自定义注释中遇到类似行为,它仍然可以帮助某人。 我在使用自定义注解和 Immutables 时遇到了类似的问题。

    类定义:

    @Value.Immutable
    @JsonDeserialize(as = ImmutableMyClass.class)
    public abstract class MyClass {
    
        @MyCustomAnnotation
        public abstract String getMyField();
        ...
    

    生成的不可变类(注意添加“java.lang.”前缀):

    @Immutable
    @CheckReturnValue
    public final class ImmutableMyClass extends MyClass {
        private final java.lang.@MyCustomAnnotation String myField;
        ...
    

    自定义注解定义:

    @Documented
    @Target({FIELD, PARAMETER, ANNOTATION_TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Constraint(validatedBy = MyCustomAnnotationValidator.class)
    public @interface MyCustomAnnotation {
    
        String DEFAULT_MESSAGE = "Validation message...";
        ...
    

    这导致“MyCustomAnnotation”根本没有被触发。

    我的问题是在“MyCustomAnnotation”中缺少 ElementType.METHOD(因为我使用的是抽象方法 getter)。

    @Documented
    @Target({FIELD, **METHOD**, PARAMETER, ANNOTATION_TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Constraint(validatedBy = MyCustomAnnotationValidator.class)
    public @interface MyCustomAnnotation {
    
        String DEFAULT_MESSAGE = "Validation message...";
        ...
    

    添加 ElementType.METHOD 后,问题消失,验证按预期触发。

    生成的不可变类:

    @Immutable
    @CheckReturnValue
    public final class ImmutableMyClass extends MyClass {
        private final @MyCustomAnnotation String myField;
        ...
    

    对于其他情况(例如,当正确使用注释的 ElementType 时,我会建议升级到最新的可能版本的依赖项(目前为 Immutables 为 2.8.2)。

    【讨论】:

      猜你喜欢
      • 2011-08-25
      • 1970-01-01
      • 1970-01-01
      • 2018-05-08
      • 1970-01-01
      • 2010-10-02
      • 2015-07-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多