英文:
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
。然后constructors
从Class
中获取一个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 Constructor
s 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 // 'this' is an instance of kotlin.reflect.KClass
val ctors: kotlin.Array<Constructor> = clazz.constructors
val ctor: java.lang.reflect.Constructor = ctors.single()
The single()
function is an extension function defined on Array
(and other types).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论