如何获取.kt文件中所有类的列表

时间:2022-03-04 20:08:19

Is it possible to grab a list of classes inside a .kt file? It appears that KDeclarationContainer is the class I am looking for, but I am unsure of how to use it.

是否可以获取.kt文件中的类列表?似乎KDeclarationContainer是我正在寻找的类,但我不确定如何使用它。

EDIT: I am using Kotlin Reflection.

编辑:我正在使用Kotlin Reflection。

1 个解决方案

#1


1  

It's not possible to obtain all classes which were declared in a specific .kt source file at runtime via reflection API, in much the same way as it's impossible to get all Java classes in a .java source file with Java reflection API. This information is simply not available at runtime.

在运行时通过反射API获取在特定.kt源文件中声明的所有类是不可能的,就像使用Java反射API在.java源文件中获取所有Java类一样。此信息在运行时根本不可用。

What is your use case? I think if you're relying on something like that, your best workaround is to declare your classes inside one top-level class, and call KClass#nestedClasses to get them all at runtime.

你的用例是什么?我认为,如果您依赖于类似的东西,那么最好的解决方法是在一个*类中声明您的类,并调用KClass #nestedClasses以在运行时获取它们。

#1


1  

It's not possible to obtain all classes which were declared in a specific .kt source file at runtime via reflection API, in much the same way as it's impossible to get all Java classes in a .java source file with Java reflection API. This information is simply not available at runtime.

在运行时通过反射API获取在特定.kt源文件中声明的所有类是不可能的,就像使用Java反射API在.java源文件中获取所有Java类一样。此信息在运行时根本不可用。

What is your use case? I think if you're relying on something like that, your best workaround is to declare your classes inside one top-level class, and call KClass#nestedClasses to get them all at runtime.

你的用例是什么?我认为,如果您依赖于类似的东西,那么最好的解决方法是在一个*类中声明您的类,并调用KClass #nestedClasses以在运行时获取它们。