4

I'm using Immutables to generate the immutable for this interface:

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

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

But the generated class field looks pretty weird to me:

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

Please see the java.lang. garbage prefixing the @Size annotation. With it there - validation does not work as expected.

With it manually removed - everything works fine. What might be the reason for this behavior? 2.5.4-2.5.6 versions checked

archie_by
  • 1,623
  • 2
  • 11
  • 10

1 Answers1

1

More than 2 years since creating an issue, but I will reply anyway as it could still help someone if they experience similar behavior with custom annotations. I ran into a similar problem when using a custom annotation and Immutables.

Class definition:

@Value.Immutable
@JsonDeserialize(as = ImmutableMyClass.class)
public abstract class MyClass {

    @MyCustomAnnotation
    public abstract String getMyField();
    ...

Generated immutable class (notice added "java.lang." prefix):

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

Custom annotation definition:

@Documented
@Target({FIELD, PARAMETER, ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = MyCustomAnnotationValidator.class)
public @interface MyCustomAnnotation {

    String DEFAULT_MESSAGE = "Validation message...";
    ...

That caused "MyCustomAnnotation" not to be triggered at all.

The problem in my case was that in "MyCustomAnnotation", ElementType.METHOD was missing (as I was using abstract method getters).

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

    String DEFAULT_MESSAGE = "Validation message...";
    ...

After adding ElementType.METHOD, the problem was gone and validation was triggered as expected.

Generated immutable class:

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

For other cases (e.g when ElementType of the annotation is used correctly, I will suggest upgrading to the latest possible versions of dependencies (2.8.2 for Immutables at this moment).