जावा प्रतिबिंब कुछ हद तक मदद करता है, लेकिन डेटा का एक गुम टुकड़ा है।इसके अलावा, प्रतिबिंब आम तौर पर कई चेक अपवाद फेंकता है जिन्हें आपको पकड़ने की आवश्यकता होगी। (मैंने कोड के बाद एक सूची शामिल की है)
"क्या कुछ" विधियां रखने वाली वस्तु क्या है? इस उदाहरण में, मैं "doOomething" विधि वाले ऑब्जेक्ट का प्रतिनिधित्व करने के लिए वेरिएबल नाम "someObject" का उपयोग करता हूं। आपको कुछ और सनसनीखेज के लिए इसे प्रतिस्थापित करने की आवश्यकता है।
इसके अलावा, केवल एक चेतावनी, यह व्युत्पन्न प्रकारों को नहीं पकड़ेगा, इसलिए यदि विधि परिभाषा दिए गए प्रकार से मेल नहीं खाती है, तो आपको एक विधि अपवाद नहीं मिलेगा।
//now I want to call doSomething method
// (1)
Method method = someObject.getClass.getMethod("doSomething",new Class[] {o.getClass()});
method.invoke(someObject, new Object[] {o});
// (2)
चेतावनी: आप जब प्रतिबिंब इस तरह का उपयोग कर निम्न अपवादों के साथ सौदा करने की जरूरत है: जहाँ तक
NoSuchMethodException - if a matching method is not found or if the name is "<init>"or "<clinit>".
NullPointerException - if name is null
SecurityException - if access to the information is denied.
IllegalAccessException - if this Method object enforces Java language access control and the underlying method is inaccessible.
IllegalArgumentException - if the method is an instance method and the specified object argument is not an instance of the class or interface declaring the underlying method (or of a subclass or implementor thereof); if the number of actual and formal parameters differ; if an unwrapping conversion for primitive arguments fails; or if, after possible unwrapping, a parameter value cannot be converted to the corresponding formal parameter type by a method invocation conversion.
InvocationTargetException - if the underlying method throws an exception.
NullPointerException - if the specified object is null and the method is an instance method.
ExceptionInInitializerError - if the initialization provoked by this method fails.
(यह नहीं एक असामान्य सूची संयोग से, प्रतिबिंब अपवाद के मामले में बहुत शोर आम तौर पर है) जैसा कि मुझे पता है कि जावा भाषा में वास्तव में * invocedynamic' बाइटकोड * का उपयोग करने का कोई तरीका नहीं है। मैं इस पर गलत साबित होना चाहता हूं, 'हालांकि। –
@ जोचिम: आह, मैंने सोचा कि जावा 7 में प्रस्तावित भाषा परिवर्तनों में से एक था। मैंने ईमानदार होने के लिए क्या किया है और क्या बाहर है, इसका ट्रैक खो गया है ... –