First, i declared an annotation
@Target(AnnotationTarget.PROPERTY)
@Retention(AnnotationRetention.RUNTIME)
annotation class PropertyAnnotation(val desc: String)
And then Container:
class Container {
@PropertyAnnotation("age")
var age: Int = -1
@PropertyAnnotation("name")
var name: String? = null
var notAnnotatedProperty: String = "not annotated"
}
And finally, code responsible for get all declared properties in MainActivity.kt
, then find a properties annotated as PropertyAnnotation
, cast it to it, and get value from it.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val container = Container()
container::class.declaredMemberProperties.forEach { prop ->
(prop.annotations.find {
it is PropertyAnnotation
} as? PropertyAnnotation)?.let {
println(it.desc)
}
}
}
And run this app on phone, you’ll get an exception when execute println(it.desc)
:
An exception occurs during Evaluate Expression Action : org.jetbrains.eval4j.VOID_VALUE cannot be cast to org.jetbrains.eval4j.AbstractValue
sometimes the exception changes to
com.sun.jdi.InternalException : Unexpected JDWP Error: 103
I add an Breakpoint at println(it.desc)
and you can find that desc=age
.
I also tried the same code in an Kotlin JVM
project with Idea, and it works ok, no exception come out. The exceptions only comes out in android project ( And Kotlin (Mobile Android/iOS)
in Idea is no exception).
My Android Studio version: 3.3.1
kotlin version: 1.3.20