The summary is at the bottom:
1.@JvmName: Modify the category corresponding to the original kt file
Usage:
@file:JvmName("Kt_ZhuJie")
package com.practice.day03
It must be written on the package name otherwise an error will be
reported. Use:
For kt files,
the class generated after decompilation: ZhujieKt is automatically generated and cannot be named as you wish. When
called on the Java side, it must be:
ZhujieKt.show();
After adding annotations:
@file:JvmName("Kt_text")
package com.practice.day03
In this way, you can change the name of the class yourself, and you can directly call it in Java
Kt_text.show();
2. @JvmField: Eliminate kotlin’s default private access rights so that the Java side can be called as public
var name = "Allen"
Before adding annotations:
Decompiling:
After adding annotations:
@JvmField
var name = "Allen"
Decompile:
In this way, it can be called normally on the Java side
3. @JvmOverloads: Make Kotlin methods overloaded and conveniently called
on the Java side. The default value of the parameters of the method in kotlin:
when annotated:
fun method(name : String, age : Int = 18){
println("我的名字是: ${
name},我今年 $age 岁了")
}
Kotlin side call:
println(method("Allen"))
According to the default value mechanism of Kotlin parameters, only one parameter can be passed in on the Kotlin side and no error will be reported. When
calling the code on the Kotlin side on the Java side, two parameters must be passed in, otherwise an error will be reported. Take a look at the
decompilation:
So on the Java side, you must Both parameters are written completely
and decompiled after adding annotations:
the generated function is this, so when calling on the Java side, you only need to pass in one parameter
. @JvmStatic: Take out the contents of the Companion object and put it in Externally, it is convenient for direct calling from the Java side.
Let’s take a look at the example directly:
before adding annotations:
class Person_Test{
companion object{
val name = "Allen"
fun showMethod(name : String){
println("${
name} 今年18岁了")
}
}
}
For this class, it is very convenient to call showMethod on the kotlin side, just like Java's Static, directly:
Person_Test.showMethod("Allen")
On the Java side it must be like this:
Person_Test.Companion.showMethod("Allen");
//Person_Test.showMethod("Allen");会报错
As for the specific reason why Java calls this, it depends on the decompiled results:
After the companion object is decompiled, a Companion class is actually generated, and then showMethod is encapsulated in it. Therefore, when calling on the Java side, Compaion must be added to call the methods in it.
After adding annotations:
@JvmStatic
fun showMethod(name : String){
println("${
name} 今年18岁了")
}
The Java side can be called directly like this:
Person_Test.showMethod("Allen");