I'm migrating a project to Kotlin, and this:
我要把一个项目搬到科特林,
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;
}
is now:
现在是:
fun provideProperties(propertiesFileName: String): Properties? {
return Properties().apply {
ObjectFactory::class.java.classLoader.getResourceAsStream(propertiesFileName).use { stream ->
load(stream)
}
}
}
very nice, Kotlin! :P
很好,芬兰湾的科特林!:P
The question is: this method looks for a .properties
file inside src/main/resources
. Using:
问题是:该方法查找src/main/resources中的.properties文件。使用:
ObjectFactory::class.java.classLoader...
it works, but using:
它的工作原理,但使用:
this.javaClass.classLoader...
classLoader
is null
...
类加载器是零…
(note that the memory address is also different)
(注意,内存地址也不同)
Why?
为什么?
Thanks
谢谢
1 个解决方案
#1
12
If you invoke javaClass
inside a lambda passed to apply
, it's called on the implicit receiver of that lambda. Since apply
turns its own receiver (Properties()
in this case) into the implicit receiver of the lambda, you're effectively getting the Java class of the Properties
object you've created. This is of course different from the Java class of ObjectFactory
you're getting with ObjectFactory::class.java
.
如果您在传递给apply的lambda中调用javaClass,那么它将调用该lambda的隐式接收者。由于apply将它自己的接收器(在本例中为Properties()))转换为lambda的隐式接收器,因此您可以有效地获得您创建的属性对象的Java类。这当然不同于您在ObjectFactory获得的Java类::class.java。
For a very thorough explanation of how implicit receivers work in Kotlin, you can read this spec document.
对于隐式接收器如何在Kotlin中工作的非常全面的解释,您可以阅读这个spec文档。
#1
12
If you invoke javaClass
inside a lambda passed to apply
, it's called on the implicit receiver of that lambda. Since apply
turns its own receiver (Properties()
in this case) into the implicit receiver of the lambda, you're effectively getting the Java class of the Properties
object you've created. This is of course different from the Java class of ObjectFactory
you're getting with ObjectFactory::class.java
.
如果您在传递给apply的lambda中调用javaClass,那么它将调用该lambda的隐式接收者。由于apply将它自己的接收器(在本例中为Properties()))转换为lambda的隐式接收器,因此您可以有效地获得您创建的属性对象的Java类。这当然不同于您在ObjectFactory获得的Java类::class.java。
For a very thorough explanation of how implicit receivers work in Kotlin, you can read this spec document.
对于隐式接收器如何在Kotlin中工作的非常全面的解释,您可以阅读这个spec文档。