0
0
Kotlinprogramming~5 mins

Kotlin annotations for Java callers (@JvmStatic, @JvmField)

Choose your learning style9 modes available
Introduction

These annotations help Kotlin code work smoothly when called from Java. They make Kotlin members easier to use in Java by changing how they appear.

You want a Kotlin function inside a companion object to look like a static method in Java.
You want a Kotlin property to be accessed directly as a field from Java without getter/setter methods.
You are writing a Kotlin library that Java developers will use and want to simplify their code.
You want to avoid extra method calls in Java for better performance or cleaner code.
Syntax
Kotlin
@JvmStatic
fun functionName() { ... }

@JvmField
var propertyName: Type = value

@JvmStatic is used on functions or properties inside companion objects or named objects.

@JvmField is used on properties to expose them as fields without getters/setters in Java.

Examples
This shows a static-like function and a field accessible directly from Java.
Kotlin
class Example {
    companion object {
        @JvmStatic
        fun greet() {
            println("Hello from Kotlin")
        }

        @JvmField
        val constant = 42
    }
}
Using @JvmStatic and @JvmField in an object for Java-friendly access.
Kotlin
object Utils {
    @JvmStatic
    fun printMessage(msg: String) {
        println(msg)
    }

    @JvmField
    val version = "1.0"
}
Sample Program

This program defines a companion object with a static-like function and a field. The main function calls the static function and prints the field.

Kotlin
class Demo {
    companion object {
        @JvmStatic
        fun sayHello() {
            println("Hello from companion object")
        }

        @JvmField
        val number = 100
    }
}

fun main() {
    Demo.sayHello()
    println("Number is: ${Demo.number}")
}
OutputSuccess
Important Notes

@JvmStatic makes Kotlin companion object functions appear as static methods in Java, so Java code can call Demo.sayHello() directly.

@JvmField exposes the property as a public field in Java, avoiding getter/setter methods.

Without these annotations, Java callers must use Kotlin's default access patterns, which can be less convenient.

Summary

@JvmStatic makes Kotlin functions in companion objects look like static methods in Java.

@JvmField exposes Kotlin properties as fields for direct access from Java.

These annotations improve Kotlin-Java interoperability and make Java code cleaner and simpler.