如何在 Kotlin 中使用 get() 定义 Class 类型 属性

How to define Class type property using get() in Kotlin

How to define a 属性 using get() in Kotlin which returns a class, 我在下面尝试过,但它是不编译

val targetActivity: Class<?>
    get() = MyActivity.class

您可以使用Class References

The most basic reflection feature is getting the runtime reference to a Kotlin class. To obtain the reference to a statically known Kotlin class, you can use the class

文字语法:

val c = MyClass::class

或者这个使用 Class<*> 而不是 Class<?>

val targetActivity: Class<*>
get() = MyActivity::class

请注意,在 Kotlin 中,您必须像这样使用 star projection, the question mark <?> won’t work; also use class references

val targetActivity: KClass<*>
    get() = MyActivity::class

如果你想要 Java Class,请使用 .java 属性:MyActivity::class.java

你需要在获得 Kotlin KClass 后使用 .java 到 return a Java Class

val targetActivity: Class<*>
  get() = MyActivity::class.java

或者,如果您想更具体地了解 return 类型

val targetActivity: Class<MyActivity>
  get() = MyActivity::class.java