我混合了scala-java spring-boot mvc项目。我正在尝试使用javax.validation.ConstraintValidator为请求bean实现自定义验证器
我在这里和其他主题中读到,最好用Java Does scala suport JSR-303 validation?编写注释

我在Scala的Java和ConstraintValidator类中编写了自定义Constraint批注,但是当我指定@Constraint(validatedBy = ScalaCustomerValidator.class)时,它给出了Type mismatch: cannot convert from Class<ScalaCustomerValidator> to Class<? extends ConstraintValidator<?,?>>[]的编译错误。我的ScalaCustomerValidator确实扩展了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 {};
}


// ConstraintValidator的标量定义

class ScalaCustomerValidator extends ConstraintValidator[ScalaCustomerValid, ScalaCustomer] { .. }


javap输出:

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();
}

最佳答案

您的问题是由于无法获取Scala对象的类引起的。 Scala编译器为对象ScalaCustomerValidator生成名为ScalaCustomerValidator $的类。 ScalaCustomerValidator $实际上实现了ConstraintValidator,无法引用它的类。
如果您尝试使用Scala:

val cl = classOf[ScalaCustomerValidator]


您也会收到编译错误。

此问题仍然存在:https://issues.scala-lang.org/i#browse/SI-2453

10-07 13:55