在C#中我可以这样做:
//This is C# static T SomeMethod() where T:new() { Console.WriteLine("Typeof T: "+typeof(T)); return new T(); } //And call the method here SomeMethod ();
但由于某种原因,我不能让它在Java中工作.
我想要做的是,在超类上创建一个静态方法,这样子类就可以转换为XML.
//This is Java, but doesn't work public static T fromXml(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 (" ");
Tom Hawtin -.. 52
public staticT fromXml(Class clazz, String xml) {
被称为:
Thing thing = fromXml(Thing.class, xml);
或更明确地:
Thing thing = MyClass.fromXml(Thing.class, xml);
更令人困惑的是,您可以拥有构造函数,这些构造函数都构造泛型类型并且本身具有泛型参数.不记得语法,并且从未见过它在愤怒中使用过(无论如何,你最好使用静态创建方法).
演员表(T)
是不安全的,你不能写T.class.因此,将T.class作为参数包含(同样JAXBContext.newInstance
如此),如果类型错误则抛出相关的异常.
public staticT fromXml(Class clazz, String xml) { try { JAXBContext context = JAXBContext.newInstance(clazz); Unmarshaller um = context.createUnmarshaller(); Object obj = um.unmarshal(new StringReader(xml)); try { return clazz.cast(obj); } catch (ClassCastException exc) { throw new RelevantException( "Expected class "+clazz+ " but was "+obj.getClass() ); } } catch (JAXBException exc) { throw new RelevantException( "Error unmarshalling XML response", exc ); } }
我相信JAXB的下一个版本(在6u14?中)对于类中的JAXB
这类事情有一些方便的方法.
public staticT fromXml(Class clazz, String xml) {
被称为:
Thing thing = fromXml(Thing.class, xml);
或更明确地:
Thing thing = MyClass.fromXml(Thing.class, xml);
更令人困惑的是,您可以拥有构造函数,这些构造函数都构造泛型类型并且本身具有泛型参数.不记得语法,并且从未见过它在愤怒中使用过(无论如何,你最好使用静态创建方法).
演员表(T)
是不安全的,你不能写T.class.因此,将T.class作为参数包含(同样JAXBContext.newInstance
如此),如果类型错误则抛出相关的异常.
public staticT fromXml(Class clazz, String xml) { try { JAXBContext context = JAXBContext.newInstance(clazz); Unmarshaller um = context.createUnmarshaller(); Object obj = um.unmarshal(new StringReader(xml)); try { return clazz.cast(obj); } catch (ClassCastException exc) { throw new RelevantException( "Expected class "+clazz+ " but was "+obj.getClass() ); } } catch (JAXBException exc) { throw new RelevantException( "Error unmarshalling XML response", exc ); } }
我相信JAXB的下一个版本(在6u14?中)对于类中的JAXB
这类事情有一些方便的方法.
在Java中,泛型是仅编译时的数据,在运行时会丢失.所以,如果你调用这样的方法,JVM就无法知道它是什么T.class
.解决此问题的常用方法是将类实例对象作为参数传递给方法,如下所示:
public staticT fromXml(Class clazz, String xml) { try { JAXBContext context = JAXBContext.newInstance(clazz); Unmarshaller um = context.createUnmarshaller(); return (T)um.unmarshal(new StringReader(xml)); } catch (JAXBException je) { throw new RuntimeException("Error interpreting XML response", je); } } fromXml(SomeSubObject.class, " ");