With Bean Validation 2.0 it is possible to also put constraints on container elements。
我无法使用它来处理Kotlin数据类:
data class Some(val someMap: Map<String, @Length(max = 255) String>)
这没有任何效果。有什么想法吗?
我创建了一个带有示例项目的存储库来复制案例:https://github.com/mduesterhoeft/bean-validation-container-constraints
答案 0 :(得分:0)
从Kotlin 1.3.70和1.4开始,可以通过设置特定的编译器选项https://kotlinlang.org/docs/reference/whatsnew14.html#type-annotations-in-the-jvm-bytecode来实现。
在任何先前版本或此支持不足的情况下,您必须编写一个自定义验证器。
用于验证集合仅包含十六进制字符串的示例一:
@Target(
AnnotationTarget.FUNCTION,
AnnotationTarget.PROPERTY_GETTER,
AnnotationTarget.PROPERTY_SETTER,
AnnotationTarget.FIELD,
AnnotationTarget.ANNOTATION_CLASS,
AnnotationTarget.CONSTRUCTOR,
AnnotationTarget.VALUE_PARAMETER
)
@Retention(AnnotationRetention.RUNTIME)
@MustBeDocumented
@Constraint(validatedBy = [HexStringElementsValidator::class])
annotation class HexStringElements(
val message: String = "must only contain hex values",
val groups: Array<KClass<*>> = [],
val payload: Array<KClass<out Any>> = []
)
class HexStringElementsValidator : ConstraintValidator<HexStringElements, Collection<Any>> {
companion object {
val pattern = "^[a-fA-F0-9]+\$".toRegex()
}
override fun isValid(value: Collection<Any>?, context: ConstraintValidatorContext?) =
value == null || value.all { it is String && pattern.matches(it) }
}
答案 1 :(得分:0)
将此配置添加到您的build.gradle
中(请注意...表示已经存在的任何内容):
时髦:
compileKotlin {
kotlinOptions {
freeCompilerArgs = [..., "-Xemit-jvm-type-annotations"]
...
}
}
科特琳DSL:
tasks.withType<KotlinCompile> {
kotlinOptions {
freeCompilerArgs = listOf(..., "-Xemit-jvm-type-annotations")
...
}
}