0

Spring Boot 2.3.1, with OpenJDK 14

Constraint Annotation:

@Documented
@Constraint(validatedBy = {MyConstraintAnnotationValidator.class})
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyConstraintAnnotation {
    String message() default "";
    Class[] groups() default {};
    Class[] payload() default {};

    Class clazz();
    // or, not sure: Class<?> clazz();
}

Constraint Annotation Validator:

public class MyConstraintAnnotationValidator implements ConstraintValidator<MyConstraintAnnotation, String> {
    @Override
    public void initialize(MyConstraintAnnotation constraintAnnotation) {
    // cac is: configurableApplicationContext
    Object obj = cac.getBean(constraintAnnotation.clazz());

    // problem: obj doesn't provide the methods to access
    // on the left side of the variable shall be also the clazz type
    // which is passed to the constraint annotation
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        return true;
    }
}

Usage of constraint annotation:

public class MyPojo {
...

@MyConstraintAnnotation(clazz = MyProperties.class)
private String field1;
...

// Getter/ Setter
}

Properties class:

@Component
@PropertySource("classpath:myproperties.properties")
@ConfigurationProperties(prefix = "myprefix")
public class MyProperties {
// fields
// Getter / Setter
}

Via the constraint annotation I want to specify my properties class to be used in the validation process within the validator class.

But within the initialize(..) method I cannot access the Getter / Setter from my properties class (MyProperties.class), because configurableApplicationContext.getBean(...) returns Object, shall create a variable and cast it to the passed class (like MyProperties.class).

How to create a variable which has on the left side the same type which is passed to the constraint annotation?

neblaz
  • 683
  • 10
  • 32
  • check if it is an instanceOf the class you want, and then cast it. – Toerktumlare Jul 13 '20 at 18:08
  • Well, how didn't I think of this :) Thanks. Would another solution be also possible, without having to cast for all possible instanceOf there might be? – neblaz Jul 13 '20 at 19:18
  • this answer seems to show a way using reflection https://stackoverflow.com/a/2127384/1840146 – Toerktumlare Jul 13 '20 at 20:40
  • Thanks for the hint and link, but it doesn't look like a solution to the question to me, but rather must doing it with 'instanceof'. – neblaz Jul 14 '20 at 05:13
  • The restriction in this question is, at least of my knowledge, that '@interface' cannot be typed, something like '@interface MyConstraintAnnotation' is not possible. – neblaz Jul 14 '20 at 05:35

0 Answers0