自创建问题 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)。