【发布时间】:2017-03-10 02:48:36
【问题描述】:
在 C# 中我实际上可以这样做:
//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>();
但由于某种原因,我无法让它在 Java 中工作。
我想做的是,在超类上创建一个静态方法,以便子类可以转换为 XML。
//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/>");
【问题讨论】: