Please consider the following classes
open class BaseClass
class MyClass private constructor(string: String): BaseClass()
And a generic function that creates an instance:
inline fun <reified T : BaseClass, reified A : Any> create(arg: A): T = T::class.java.getConstructor(arg::class.java).newInstance(arg)
The following test fails:
@Test(expected = IllegalAccessException::class)
fun `should throw an IllegalAccessException`() {
val test: MyClass = create("test")
}
because a java.lang.NoSuchMethodException is actually thrown. The JavaDoc for Constructor.newInstance() states:
@exception IllegalAccessException if this {@code Constructor} object is enforcing Java language access control and the underlying constructor is inaccessible.
A private constructor matches my expectation of an "inaccessible constructor". Why does this example throw a NoSuchMethodException instead and under which circumstances can it throw an IllegalAccessException?