作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
请考虑以下类(class)
open class BaseClass
class MyClass private constructor(string: String): BaseClass()
还有一个创建实例的通用函数:
inline fun <reified T : BaseClass, reified A : Any> create(arg: A): T = T::class.java.getConstructor(arg::class.java).newInstance(arg)
以下测试失败:
@Test(expected = IllegalAccessException::class)
fun `should throw an IllegalAccessException`() {
val test: MyClass = create("test")
}
因为一个
java.lang.NoSuchMethodException
实际上是抛出。
Constructor.newInstance()
的 JavaDoc状态:
@exception IllegalAccessException if this {@code Constructor}objectis enforcing Java language access control and the underlyingconstructor is inaccessible.
NoSuchMethodException
而是在什么情况下可以抛出
IllegalAccessException
?
最佳答案
getConstructor
方法将尝试仅从公共(public)构造函数列表中选择构造函数,不会考虑私有(private)构造函数。由于找不到公开匹配,它会抛出 NoSuchMethodException
.IllegalAccessException
,另一方面,将被 newInstance
抛出方法如果你使用 getDeclaredConstructor
相反,因为此特定方法从所有可用构造函数中选择构造函数,而不仅仅是公共(public)构造函数,因此将检索示例中的私有(private)构造函数,尽管不可访问。
下面会抛出IllegalAccessException
:
T::class.java.getDeclaredConstructor(arg::class.java).newInstance(arg)
val ct = T::class.java.getDeclaredConstructor(arg::class.java)
ct.trySetAccessible()
return ct.newInstance(arg)
关于java - Kotlin/Java 泛型 : when to expect an IllegalAccessException during instantiation?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62032527/
我是一名优秀的程序员,十分优秀!