बिना सी # में मैं वास्तव में यह कर सकते हैं:जेनेरिक विधि सामान्य तर्क
//This is C#
static T SomeMethod<T>() where T:new()
{
Console.WriteLine("Typeof T: "+typeof(T));
return new T();
}
//And call the method here
SomeMethod<SomeClassName>();
लेकिन किसी कारण मैं इसे जावा में काम करने के लिए नहीं मिल सकता है के लिए।
मैं जो चीज करना चाहता हूं वह सुपरक्लास पर एक स्थिर विधि बनाने के लिए है, इसलिए उप-वर्गों को एक्सएमएल में परिवर्तित किया जा सकता है।
//This is Java, but doesn't work
public static T fromXml<T>(String xml) {
try {
JAXBContext context = JAXBContext.newInstance(T.class);
Unmarshaller um = context.createUnmarshaller();
return (T)um.unmarshal(new StringReader(xml));
} catch (JAXBException je) {
throw new RuntimeException("Error interpreting XML response", je);
}
}
//Also the call doesn't work...
fromXml<SomeSubObject>("<xml/>");
भी संकलन नहीं होगा ... आप T.class – pgras
नहीं लिख सकते हैं मैं विधि में T.class बारे में मतलब नहीं था। मैंने एक Argumnet के रूप में कहा। और कॉलिंग फ़ंक्शन नहीं हो सकता है (या यह एक Argumnet के रूप में पारित हो सकता है)। –
नया इंस्टेंस (टी। क्लास) एक प्रतिलिपि और पेस्ट था जिसे मैंने नहीं देखा था। अभी भी सवाल एक सामान्य विधि लिखने के बारे में प्रतीत होता है। –