2017-03-03 73 views
10

我迁移项目科特林,这:科特林:MyClass的:: class.java VS this.javaClass

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) 
     } 
    } 
} 

非常漂亮,科特林! :P

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

ObjectFactory::class.java.classLoader... 

它的工作原理,但使用:

this.javaClass.classLoader... 

classLoadernull ...

enter image description here

enter image description here

enter image description here

(注意内存地址也不同)

为什么?

感谢

+0

'this.javaClass'的值是什么? – chrylis

+0

我编辑了我的问题。 –

+0

您是否在运行时或编译时遇到错误? – chrylis

回答

9

如果调用javaClass传递给apply拉姆达里面,这就是所谓的对拉姆达的隐含接收器。由于apply将它自己的接收器(在这种情况下为Properties())转换为lambda的隐式接收器,所以您实际上获得了您创建的Properties对象的Java类。当然这与你使用ObjectFactory::class.java获得的Java类ObjectFactory不同。

有关隐式接收器如何在Kotlin中工作的详细说明,可以阅读this spec document

+0

谢谢,现在很清楚 –