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

时间:2021-11-18 20:07:51

How to define a property using get() in Kotlin which returns a class, I was trying below, but it's not compiling

如何在Kotlin中使用get()定义一个属性,它返回一个类,我在下面尝试,但它不是在编译

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

3 个解决方案

#1


4  

You can use 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

最基本的反射功能是获取Kotlin类的运行时引用。要获得对静态已知Kotlin类的引用,可以使用该类

literal syntax:

文字语法:

val c = MyClass::class

or this use Class<*> instead of Class<?>

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

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

#2


3  

Be aware that in Kotlin you have to use star projection, the question mark <?> won’t work; also use class references like this:

请注意,在Kotlin中你必须使用星形投影,问号<?>将不起作用;也使用这样的类引用:

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

If you want to have a Java Class, use the .java property: MyActivity::class.java

如果要使用Java类,请使用.java属性:MyActivity :: class.java

#3


1  

you need to use .java after getting a Kotlin KClass to return a Java Class

在获得Kotlin KClass返回Java类之后,您需要使用.java

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

Or, if you want to be more specific about the return type

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

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

#1


4  

You can use 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

最基本的反射功能是获取Kotlin类的运行时引用。要获得对静态已知Kotlin类的引用,可以使用该类

literal syntax:

文字语法:

val c = MyClass::class

or this use Class<*> instead of Class<?>

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

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

#2


3  

Be aware that in Kotlin you have to use star projection, the question mark <?> won’t work; also use class references like this:

请注意,在Kotlin中你必须使用星形投影,问号<?>将不起作用;也使用这样的类引用:

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

If you want to have a Java Class, use the .java property: MyActivity::class.java

如果要使用Java类,请使用.java属性:MyActivity :: class.java

#3


1  

you need to use .java after getting a Kotlin KClass to return a Java Class

在获得Kotlin KClass返回Java类之后,您需要使用.java

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

Or, if you want to be more specific about the return type

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

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