Kotlin noarg plugin:只能通过 java 反射访问的构造函数



我的设置有问题,但我无法弄清楚它是什么。 从 Kotlin 编译器插件中,我有以下信息。

no-arg 编译器插件为具有特定注释的类生成一个额外的零参数构造函数。

生成的构造函数是合成的,因此不能直接从 Java 或 Kotlin 调用,但可以使用反射调用它。

也就是说,我认为我可以通过java和kotlin Reflection访问noarg构造函数,但我只能通过java Reflection访问它。这是预期的行为,还是我做错了什么?

build.gradle

plugins {
id 'org.jetbrains.kotlin.jvm' version '1.3.50'
id "org.jetbrains.kotlin.plugin.noarg" version "1.3.50"
id 'application'
id 'java'
}
repositories {
mavenCentral()
jcenter()
}
dependencies {
implementation 'org.jetbrains.kotlin:kotlin-stdlib-jdk8'
compile group: 'org.jetbrains.kotlin', name: 'kotlin-reflect', version: '1.3.50'
}
noArg {
annotation('noargdemo.Entity')
}
application {
mainClassName = 'noargdemo.AppKt'
}
package noargdemo
import kotlin.reflect.full.createInstance
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.RUNTIME)
annotation class Entity
@Entity
data class Employee(
val firstName : String,
val secondName : String
)
fun main(args: Array<String>) {
val kotlinConstructors = Employee::class.constructors // size is 1
val javaConstructors = Employee::class.java.constructors // size is 2
val instance1 = Employee::class.java.getConstructor().newInstance() // works
val instance2 = Employee::class.createInstance() // doesnt work
}

这是预期的行为,即使在您引用的描述中也说明:

生成的构造函数是合成的,因此不能直接从 Java 或 Kotlin 调用,但可以使用反射调用它。

合成方法是编译器为内部目的生成的方法,它们不能从源代码手动调用,但它们对于反射是可见的。

您可以使用 Method.isSynthetic 检查方法是否是合成的:https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Method.html#isSynthetic--

最新更新