I have mixed scala-java spring-boot mvc project. I am trying to implement custom validator for request bean using javax.validation.ConstraintValidator
I read here and other threads that its better to write annotation in Java Does scala suport JSR-303 validation?
I wrote custom Constraint annotation in Java and ConstraintValidator class in scala, but when I specify @Constraint(validatedBy = ScalaCustomerValidator.class) It gives compile error that Type mismatch: cannot convert from Class<ScalaCustomerValidator> to Class<? extends ConstraintValidator<?,?>>[]
Type mismatch: cannot convert from Class<ScalaCustomerValidator> to Class<? extends ConstraintValidator<?,?>>[]
. My ScalaCustomerValidator does extends ConstraintValidator.
//java
@Constraint(validatedBy = ScalaCustomerValidator.class) //Type mismatch error
@Target(value = ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface ScalaCustomerValid {
String message() default "Invalid tab to filter combination";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
//scala definition of ConstraintValidator
class ScalaCustomerValidator extends ConstraintValidator[ScalaCustomerValid, ScalaCustomer] { .. }
javap output:
javap ScalaCustomerValidator
Warning: Binary file ScalaCustomerValidator contains com.ScalaCustomerValidator
Compiled from "ScalaCustomerValidator.scala"
public class com.ScalaCustomerValidator implements javax.validation.ConstraintValidator<com.ScalaCustomerValid, com.ScalaCustomer> {
public void initialize(com.ScalaCustomerValid);
public boolean isValid(com.ScalaCustomer, javax.validation.ConstraintValidatorContext);
public boolean isValid(java.lang.Object, javax.validation.ConstraintValidatorContext);
public void initialize(java.lang.annotation.Annotation);
public com.ScalaCustomerValidator();
}
Your problem is caused by impossibility of getting class of scala object. Scala compiler generates class named ScalaCustomerValidator$ for object ScalaCustomerValidator. ScalaCustomerValidator$ actually implements ConstraintValidator and there is no way to reference it's class. If you try in scala:
val cl = classOf[ScalaCustomerValidator]
you'll get the compile error as well.
This problem is still open: https://issues.scala-lang.org/i#browse/SI-2453
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.