2017-03-03 18 views
10

मैं Kotlin के लिए एक परियोजना की ओर पलायन कर रहा हूँ, और यह:Kotlin: MyClass :: class.java बनाम 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) 
     } 
    } 
} 

बहुत अच्छा, Kotlin! : पी

सवाल यह है: यह विधि के अंदर .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()) को बदल देता है, इसलिए आप प्रभावी रूप से Properties ऑब्जेक्ट की जावा क्लास प्राप्त कर रहे हैं। यह ObjectFactory की जावा क्लास से बिल्कुल अलग है, आपको ObjectFactory::class.java मिल रहा है।

कोटलिन में अंतर्निहित रिसीवर कैसे काम करते हैं, इसकी एक बहुत अच्छी व्याख्या के लिए, आप this spec document पढ़ सकते हैं।

+0

धन्यवाद, अब मुझे स्पष्ट है –

संबंधित मुद्दे