1
\$\begingroup\$

So, I am trying to implement an annotation in Kotlin, and it works, but I definitely feel like I could do a lot better. Below is the code and some areas I think could be improved. The purpose of this validator is to be applied to a field/getter and fail if it's not of a certain type (please don't ask why I need to do this)

Improvements:

  1. For starters, It's not clear to me how I can get it to have a default error message of ${field} must be of type {type} When I try that, I get no output
  2. If I look at the case of @NotNull I can see that it has no validator code at all, and yet still works as well as has proper interpolation.

The annotation:

package com.company.validators


import javax.validation.Constraint
import javax.validation.Payload
import kotlin.reflect.KClass

@Target(AnnotationTarget.FIELD, AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.PROPERTY_GETTER)
@Retention(AnnotationRetention.RUNTIME)
@Constraint(validatedBy = [InstanceOfValidator::class])
annotation class InstanceOf(
    val type: KClass<*>,
    val message: String = "{com.company.validators.InstanceOf.message}",
    val groups: Array<KClass<*>> = [],
    val payload: Array<KClass<out Payload>> = []
)

The validator:

package com.company.validators

import javax.validation.ConstraintValidator
import javax.validation.ConstraintValidatorContext
import kotlin.reflect.KClass

class InstanceOfValidator : ConstraintValidator<InstanceOf,Any> {


    private var type: KClass<*>? = null

    override fun initialize(annotation: InstanceOf) {
        this.type = annotation.type
    }

    override fun isValid(value: Any?, context: ConstraintValidatorContext?): Boolean {
        return value != null && (type?.isInstance(value) ?: false)
    }

}

And here is an example of it's usage:

class PSRRaw {

    @get:NotNull
    @get:InstanceOf(Double::class)
    var bugId: Any? = null
}
\$\endgroup\$

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.