Java构造函数reflection抛出与密封类的exception

我在Kotlin项目中有以下密封课程:

sealed class Test { abstract val test: String @NoArg data class Test1( override val test: String ) : Test() @NoArg data class Test2( override val test: String ) : Test() } 

@NoArg注释是一个标记,编译器被配置为为这些类生成一个无参数构造函数。

我的问题是,尝试使用Javareflection结果实例化Test1Test2中的以下exception:

 Exception in thread "main" java.lang.reflect.InvocationTargetException at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:423) at MainKt.main(Main.kt:27) Caused by: java.lang.IllegalAccessError: tried to access method Test.()V from class Test$Test1 at Test$Test1.(Main.kt) ... 5 more 

当我尝试使用Spring Data Mongo从Mongo数据库加载这些类的实例时,我最初遇到了这个问题。

我在这个测试中用来实例化它们的代码如下:

 val javaConstructor = Test.Test1::class.java.getConstructor() ?: error("Did not find constructor") val instance = javaConstructor.newInstance() 

我目前的解决方法是只使用解决exception的密封类。 有没有一种方法可以保持密封的类,并使Javareflection正确工作? 我不认为这是相当有意的行为,但也许有某种原因呢? 如果是这样,我有兴趣听到它是什么。

我在这里有一个我的问题的例子: https : //github.com/mhlz/playground