什么是java.constructors.single()?

huangapple go评论76阅读模式
英文:

What is java.constructors.single()?

问题

我正在学习如何在 Kotlin 中评估脚本,我在 BasicJvmScriptEvaluator 中看到了以下代码:

val ctor = java.constructors.single()

val saveClassLoader = Thread.currentThread().contextClassLoader
Thread.currentThread().contextClassLoader = this.java.classLoader
return try {
    ctor.newInstance(*args.toArray())
} finally {
    Thread.currentThread().contextClassLoader = saveClassLoader
}

我不理解 java.constructors.single() 这段代码,似乎没有名为 java.constructors 的包。我应该如何理解这段代码?

英文:

I'm learning Kotlin how to eval scripts, and I saw the code in BasicJvmScriptEvaluator like the following:

    val ctor = java.constructors.single()

    val saveClassLoader = Thread.currentThread().contextClassLoader
    Thread.currentThread().contextClassLoader = this.java.classLoader
    return try {
        ctor.newInstance(*args.toArray())
    } finally {
        Thread.currentThread().contextClassLoader = saveClassLoader
    }

I don't understand the code java.constructors.single(), there is no package named java.constructors. How should I understand this code?

答案1

得分: 5

很重要的一点是要意识到你正在一个扩展函数中操作一个KClass的实例。所以java实际上是对this.java的调用,它返回与KClass关联的java.lang.Class。然后constructorsClass中获取一个Constructor数组,而single()获取该数组中的一个(如果有且仅有一个,否则将抛出异常)。

如果将代码展开为多行,可能更容易理解正在发生的情况:

val clazz: java.lang.Class = this.java // 'this'是kotlin.reflect.KClass的一个实例
val ctors: kotlin.Array<Constructor> = clazz.constructors
val ctor: java.lang.reflect.Constructor = ctors.single()

single()函数是定义在Array(和其他类型)上的扩展函数

英文:

It's important to realize you're in an extension function operating on an instance of KClass. So the java is actually an invocation of this.java which returns the java.lang.Class associated with the KClass. Then the constructors gets an array of Constructors from the Class and single() gets the one (and only, else an exception is thrown) element in that array.

If you expand the code into multiple lines it may be easier to see what's going on:

val clazz: java.lang.Class = this.java // &#39;this&#39; is an instance of kotlin.reflect.KClass
val ctors: kotlin.Array&lt;Constructor&gt; = clazz.constructors
val ctor: java.lang.reflect.Constructor = ctors.single()

The single() function is an extension function defined on Array (and other types).

huangapple
  • 本文由 发表于 2020年10月21日 18:03:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/64461190.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定