首页 > 解决方案 > 为什么Intent中的类有“::class.java”后缀?

问题描述

Kotlin 中的一个意图:

val intent = Intent(this, OtherActivity::class.java)

为什么不能这样:

val intent = Intent(this, OtherActivity)

?

标签: androidkotlin

解决方案


该 Intent 构造函数的第二个参数需要您要创建的 Activity的类。虽然只使用类名来获取类会很方便OtherActivity,但 Java(和 Kotlin)语法不支持这一点。

相反,Java 提供.class语法 ( OtherActivity.class),Kotlin::class为 Kotlin 类提供语法,而::class.java( OtherActivity::class.java) 为 Java 类提供,这正是 Intent 构造函数所需要的。


推荐阅读