से एक वर्ग का दृष्टांत को this question about the Groovy way to dynamically invoke a static method का जवाब बहुत मददगार थे, लेकिन मैं निम्नलिखित मामले में परेशानी आ रही:ग्रूवी डायनामिक स्ट्रिंग
class Item {
def id = 1
def data = [ "a", "b" ]
}
मैं तो:
मैं एक साधारण ग्रूवी वर्ग परिभाषित
class Util {
static def main(args) {
def cls = "Item" as Class
def instance = cls.newInstance()
println instance.toString()
}
}
Util.groovy एक ही फ़ोल्डर में है के रूप में Item.groovy
: एक सरल उपयोगिता वर्ग गतिशील मद वर्ग लोड करने के लिए चाहता है कि परिभाषितजब मैं Util.groovy मैं निम्नलिखित त्रुटि मिलती है चलाने का प्रयास:
Caught: org.codehaus.groovy.runtime.typehandling.GroovyCastException:
Cannot cast object 'Item' with class 'java.lang.String'
to class 'java.lang.Class' due to:
java.lang.ClassNotFoundException: Item
at Util.main(Util.groovy:3)
एक ही तरीका है कि मैं यह काम कर सकता है groovyc का उपयोग कर Item.groovy precompile करने के द्वारा किया गया था, लेकिन इस किया जा रहा है की बात याद करते हैं ग्रूवी :)
आपको शायद 'this.class' को' this.getClass() 'में बदलना चाहिए। [आम तौर पर संपत्ति या मानचित्र लुकअप (या invokeMethod ओवरराइड) से बचने के लिए पूर्ण विधि का उपयोग करने की अनुशंसा की जाती है (http://groovy.329449.n5.nabble.com/class-vs-getClass-td368617.html)। – OverZealous
जब हम जानते हैं कि यह मानचित्र क्यों नहीं है परेशान क्यों? गतिशील गले लगाओ! ;-) –
यह काम किया! धन्यवाद टिम! :) –