科特林:MyClass::class.java 与 this.javaClass

Kotlin: MyClass::class.java vs this.javaClass

我正在将一个项目迁移到 Kotlin,并且:

public static Properties provideProperties(String propertiesFileName) {
    Properties properties = new Properties();
    InputStream inputStream = null;
    try {
        inputStream = ObjectFactory.class.getClassLoader().getResourceAsStream(propertiesFileName);
        properties.load(inputStream);
        return properties;
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return null;
}

现在是:

fun provideProperties(propertiesFileName: String): Properties? {
    return Properties().apply {
        ObjectFactory::class.java.classLoader.getResourceAsStream(propertiesFileName).use { stream ->
            load(stream)
        }
    }
}

非常好,Kotlin! :P

问题是:此方法在 src/main/resources 中查找 .properties 文件。使用:

ObjectFactory::class.java.classLoader...

有效,但使用:

this.javaClass.classLoader...

classLoadernull...

(注意内存地址也不一样)

为什么?

谢谢

如果您在传递给 apply 的 lambda 中调用 javaClass,则会在该 lambda 的 隐式接收器 上调用它。由于 apply 将其自己的接收器(在本例中为 Properties())转换为 lambda 的隐式接收器,因此您实际上得到了 [=14= 的 Java class ] 你创建的对象。这当然不同于 ObjectFactory::class.java.

ObjectFactory 的 Java class

有关 Kotlin 中隐式接收器如何工作的非常详尽的解释,您可以阅读 this spec document