Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Public fields for Java compatibility

I found recent interest in Kotlin as a language, because the platform we develop for is Java 6 based and hence lacks any syntactic sugar the recent years brought to Java.

There's but one thing that makes it impossible to use Kotlin over Java in development, that is, the platform we develop for uses some reflection internally and requires members to be public. It won't work otherwise.

So, the bytecode generated from the Kotlin file in fact produces public getters and setters, the fields themselves yet remain private.

Is there a way to overcome this, so I get real public fields?

I am aware of the design failure that requires public fields, but the system is kind of a black box to us, we cannot change the fact that it has to be this way.

like image 397
John Smith Avatar asked Dec 08 '16 12:12

John Smith


People also ask

What are public fields in Java?

public is a Java keyword which declares a member's access as public. Public members are visible to all other classes. This means that any other class can access a public field or method. Further, other classes can modify public fields unless the field is declared as final .

How to access a public field in Java?

If you have a Class object, you can obtain its public fields (including inherited fields) by calling getFields() on the Class object.

Does kotlin have public fields?

It won't work otherwise. So, the bytecode generated from the Kotlin file in fact produces public getters and setters, the fields themselves yet remain private.


1 Answers

The annotation @JvmField should help you. It makes the Kotlin-compiler expose the property as a field on the JVM. See here: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.jvm/-jvm-field/

like image 186
marstran Avatar answered Oct 14 '22 13:10

marstran