2

I've been trying some stuff from kotlin.reflection during my project, and got stuck on something what occurs to me as hard to understand, I have declared object as follows:

object WebsiteMapping
{
    const val ADMIN = "/admin"
}

once I call:

Arrays
  .stream(WebsiteMapping::class.java.declaredFields)
  .forEach { field -> println(field.type) }

what I get is:

class java.lang.String
class mapping.WebsiteMapping

When I looked a little bit into what is behind declaredFields invocation I grasped why it works as it is, but is there any convenient way of taking only declared consts within that object without getting also root of the whole structure?

1 Answer 1

4

The field with the type class mapping.WebsiteMapping is, basically, not the root of the structure but a special field generated in the object type that holds the reference to the singleton object.

In Kotlin, this field is named INSTANCE by convention. You can therefore filter the fields that you get from the class as follows:

WebsiteMapping::class.java.declaredFields
    .filter { it.name != "INSTANCE" }
    .forEach { println(it.type) }

Another solution is to switch from java.reflect.* to the Kotlin reflection API kotlin.reflect (needs a dependency on the kotlin-reflect module), which automatically filters the property:

WebsiteMapping::class.memberProperties
    .forEach { println(it.returnType) }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.