获取“Class”来自泛型类型T的对象 [英] Get "Class" object from generic type T
问题描述
我想制作返回XML文档的Object表示的泛型函数(使用JAXB)。我需要将class对象传递给JAXBContext构造函数,但是我怎样才能从T中获得它?
public< T> readXmlToObject(String xmlFileName,T jaxbClass){
JAXBContext context = JAXBContext.newInstance(T.class); // T.class - 这里错误,如何得到它?
.......
}
$ b
public< T> 传递类对象,而且很容易。 T readXmlToObject(String xmlFileName,Class< T> jaxbClass){
JAXBContext context = JAXBContext.newInstance(jaxbClass); // T.class - 这里错误,如何得到它?
Object o = context.createUnmarshaller()。unmarshal(new File(xmlFileName));
返回jaxbClass.cast(o);
$ b
这里的想法是因为你不能从对象,你必须以相反的方式来做:从类开始,然后操纵对象以匹配类型参数。
I want to make generic function that return Object representation of XML document (using JAXB). I need to pass "class" object to JAXBContext constructor, but how I can get it from T?
public <T> readXmlToObject(String xmlFileName, T jaxbClass) {
JAXBContext context = JAXBContext.newInstance(T.class); // T.class - here error, how to get it?
.......
}
解决方案 Pass the class object instead and it's easy.
public <T> T readXmlToObject(String xmlFileName, Class<T> jaxbClass) {
JAXBContext context = JAXBContext.newInstance( jaxbClass ); // T.class - here error, how to get it?
Object o = context.createUnmarshaller().unmarshal( new File( xmlFileName ) );
return jaxbClass.cast( o );
}
The idea here is that since you can't extract the type parameter from the object, you have to do it the other way around: start with the class and then manipulate the object to match the type parameter.
这篇关于获取“Class”来自泛型类型T的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!