Annotations in kotlin ‐ @JvmField - devrath/KotlinAlchemy GitHub Wiki
Observation
- Note the
namevariable is annotated as@JvmField. - This indicated to the compiler that this field can directly accessed by the
javaclass. - Note the
javaclass will not need the getter method to access it. - It can be done the same way the kotlin class would do it.
Code
Person.kt
data class Person(@JvmField val name: String, val age:Int)
DemoKotlinJvmAnnotation.kt
class DemoKotlinJvmAnnotation {
fun initiate() {
val person = Person("Suresh", 23)
PrintUtils.printLog(person.name)
PrintUtils.printLog(person.age.toString())
}
}
DemoJavaJvmAnnotation.java
public class DemoJavaJvmAnnotation {
public void initiate() {
// Compiler will understand getter and setter will not be needed and we can access the field directly
Person person = new Person("Suresh",23);
PrintUtils.INSTANCE.printLog(person.name); // Observe we have not used the getter method still able to access the field
PrintUtils.INSTANCE.printLog(String.valueOf(person.getAge())); // Since the JVM annotation is not present for this field, We need a getter method to access the field
}
}