Class.getClass() for Kolin class using Java API


#1

How can I get the Class for a Kotlin class using Java API?

I’m implementing Android app using Data Binding and some of my binding expressions require KProperty1 to be passed as a parameter. As far as I know, the code that goes into binding expression must be Java only, so I cannot call MyClass::myProperty. Instead, I want to have something like:

MyClassKt.getClass().getField(`myField`).kotlinProperty

Is it possible?


#2

Have you tried My class::class.java?


#3

I cannot use :: operator in the binding expression.


#4

The file you’re writing the binding expression, is it a Java file or a kotlin file?


#5

Is is android’s layout XML file. The value of an attribute to be exact. I want to write something like:
android:text="@{MyClassKt.getClass().getField(`myField`).kotlinProperty.name}"


#6

I don’t think that android data binding supports the kotlin reflection library. You will have to address things like from Java


#7

Data binding library does not support Kotlin indeed. Only Java.
I just got curious about this, because I can call Kotlin’s top-level functions from Java.


#8

Of course you can. It doesn’t mean you cannot use databinding with Kotlin. It means that you are restricted to the same API that Java users get (the databinding expressions are modelled after Java but effectively their own language that is transpiled into Java). To get the actual name of a Kotlin property you will need to use the Kotlin reflection library. This is possible, but is not going to be pretty (from Java) and quite heavyweight for what you are doing (the field name is static per definition - it is precompiled). Your property name also lacks the ability to be translated.