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

Mat*_*aga 23 java classloader kotlin

我正在将项目迁移到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;
}
Run Code Online (Sandbox Code Playgroud)

就是现在:

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

非常好,Kotlin!:P

问题是:这个方法.properties在里面查找文件src/main/resources.使用:

ObjectFactory::class.java.classLoader...
Run Code Online (Sandbox Code Playgroud)

它有效,但使用:

this.javaClass.classLoader...
Run Code Online (Sandbox Code Playgroud)

classLoadernull......

在此输入图像描述

在此输入图像描述

在此输入图像描述

(注意内存地址也不同)

为什么?

谢谢

Ale*_*lov 16

如果javaClass在传入的lambda内部调用,则在该lambda apply隐式接收器上调用它.由于apply将自己的接收器(Properties()在本例中)转换为lambda的隐式接收器,因此您可以有效地获取Properties您创建的对象的Java类.这当然不同于ObjectFactory你正在使用的Java类ObjectFactory::class.java.

有关隐式接收器如何在Kotlin中工作的非常详尽的解释,您可以阅读此规范文档.