I’m trying to write a ConstraintValidator in kotli...
# spring
m
I’m trying to write a ConstraintValidator in kotlin, and not finding any good examples. In java you define an @interface, and then reference a class that extends Constraint Validator. In kotlin, you do an
annotation class
instead - but is it otherwise the same, a separate class that the annotation class points to? at first I thought maybe I would just put the behavior in the
annotation class
- but it seems problematic to extend
ConstraintValidator
since that needs to be typed as the annotation type. This is not my usual area, so I’m just kind of trying things.
l
I’ve done it this way:
Copy code
@Target(AnnotationTarget.FIELD, AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
@Constraint(validatedBy = [CnpjAnnotationValidator::class])
annotation class Cnpj(
    val message: String = "",
    val groups: Array<KClass<*>> = [],
    val payload: Array<KClass<out Payload>> = []
)

class CnpjAnnotationValidator : ConstraintValidator<Cnpj, String> {

  override fun initialize(constraintAnnotation: Cnpj) {

  }

  override fun isValid(value: String?, context: ConstraintValidatorContext?): Boolean {
    return try {
      CNPJ_VALIDATOR.assertValid(value)
      true
    } catch (ex: InvalidStateException) {
      false
    }
  }

  companion object {
    private val CNPJ_VALIDATOR = CNPJValidator()
  }

}
m
Cool - I was headed in that direction - although the companion object is not something i would have guessed. Is that what I was missing for the upper
@Constraint
error?
l
That’s just for holding a singleton reference to another class, not related to the annotation / validator
m
K. Step one - it’s validating. Step two - figure out what that context thing is doing.
Thanks!