Add the code for article "Kotlin Annotations" (BAEL-2579) (#6540)

This commit is contained in:
Andrey Shcherbakov 2019-03-15 23:45:56 +01:00 committed by maibin
parent 4df665a579
commit 2b28336cd6
5 changed files with 97 additions and 0 deletions

View File

@ -0,0 +1,7 @@
package com.baeldung.annotations
@Target(AnnotationTarget.FIELD)
annotation class Positive
@Target(AnnotationTarget.FIELD)
annotation class AllowedNames(val names: Array<String>)

View File

@ -0,0 +1,3 @@
package com.baeldung.annotations
class Item(@Positive val amount: Float, @AllowedNames(["Alice", "Bob"]) val name: String)

View File

@ -0,0 +1,7 @@
package com.baeldung.annotations
fun main(args: Array<String>) {
val item = Item(amount = 1.0f, name = "Bob")
val validator = Validator()
println("Is instance valid? ${validator.isValid(item)}")
}

View File

@ -0,0 +1,38 @@
package com.baeldung.annotations
/**
* Naive annotation-based validator.
* @author A.Shcherbakov
*/
class Validator() {
/**
* Return true if every item's property annotated with @Positive is positive and if
* every item's property annotated with @AllowedNames has a value specified in that annotation.
*/
fun isValid(item: Item): Boolean {
val fields = item::class.java.declaredFields
for (field in fields) {
field.isAccessible = true
for (annotation in field.annotations) {
val value = field.get(item)
if (field.isAnnotationPresent(Positive::class.java)) {
val amount = value as Float
if (amount < 0) {
return false
}
}
if (field.isAnnotationPresent(AllowedNames::class.java)) {
val allowedNames = field.getAnnotation(AllowedNames::class.java)?.names
val name = value as String
allowedNames?.let {
if (!it.contains(name)) {
return false
}
}
}
}
}
return true
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.annotations
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Test
class ValidationUnitTest {
@Test
fun whenAmountIsOneAndNameIsAlice_thenTrue() {
assertTrue(Validator().isValid(Item(1f, "Alice")))
}
@Test
fun whenAmountIsOneAndNameIsBob_thenTrue() {
assertTrue(Validator().isValid(Item(1f, "Bob")))
}
@Test
fun whenAmountIsMinusOneAndNameIsAlice_thenFalse() {
assertFalse(Validator().isValid(Item(-1f, "Alice")))
}
@Test
fun whenAmountIsMinusOneAndNameIsBob_thenFalse() {
assertFalse(Validator().isValid(Item(-1f, "Bob")))
}
@Test
fun whenAmountIsOneAndNameIsTom_thenFalse() {
assertFalse(Validator().isValid(Item(1f, "Tom")))
}
@Test
fun whenAmountIsMinusOneAndNameIsTom_thenFalse() {
assertFalse(Validator().isValid(Item(-1f, "Tom")))
}
}