निम्नलिखित कोड एक एंड्रॉइड लाइब्रेरी से है जिसे बुटरकिनीफ कहा जाता है। मैं यह पता लगा रहा हूं कि यह कैसे काम करता है।रिटर्न प्रकार के आधार पर जावा जेनरिक कास्ट?
@SuppressWarnings("unchecked")
public static <T> T cast(Object o){
try {
return (T) o;
} catch (ClassCastException e){
throw new AssertionError("Error");
}
}
और उपयोग::
@SuppressWarnings("unchecked") // That's the point.
public <T> T castParam(Object value, String from, int fromPosition, String to, int toPosition) {
try {
return (T) value;
} catch (ClassCastException e) {
throw new IllegalStateException("Parameter #"
+ (fromPosition + 1)
+ " of method '"
+ from
+ "' was of the wrong type for parameter #"
+ (toPosition + 1)
+ " of method '"
+ to
+ "'. See cause for more info.", e);
}
}
मैं इस समारोह के व्यवहार को पुन: करने की कोशिश की
Object o = new String("test");
Double d = cast(o);
लेकिन अपवाद कभी नहीं पकड़ा नहीं है, यह लाइन पर फेंक दिया जाता है जब विधि कहा जाता है। ऐसा क्यों है?
इसके अलावा, यह वास्तव में कैसे काम करता है? विधि कैसे पता चलेगी कि क्या डालना है?
यहां किसी और ने बिल्कुल ऐसा करने की कोशिश की: http://stackoverflow.com/questions/14524751/cast-object-to-generic-type-for-returning – SJuan76
लाइब्रेरी तब कैसे काम करती है? – Greyshack