For example, I want to get ["title", "body"]
from following class.
import com.fasterxml.jackson.annotation.JsonProperty
data class MyClass (
@JsonProperty("title") var titleValue: String,
@JsonProperty("body") var bodyValue: String
)
CodePudding user response:
Your example shows a data class
, where the properties are usually declared inside the primary constructor.
Since the @JsonProperty
is an annotation written in Java, we cannot use Kotlin class reflection to find the annotation, and instead have to use the Java class.
After getting the Java Class, we can find the primary constructor and iterate over it's arguments/parameters. Finally, we iterate over the parameters to find and map @JsonProperty
s to their value:
fun getJsonPropertyValues(target: KClass<out Any>): List<String> {
val cls = target.java
return cls.declaredConstructors[0].parameters.flatMap { parameter ->
parameter.annotations
.filterIsInstance<JsonProperty>()
.map { it.value }
}
}
// usage:
val list = getJsonPropertyValues(MyClass::class)
println(list)
> [title, body]
This will not work on fields which are declared and annotated outside of the primary constructor. If you want to support these cases, you need to modify the code snippet to iterate over the other members of the class as well.