gpt4 book ai didi

java - 如何用java编写T.class?

转载 作者:行者123 更新时间:2023-12-02 07:29:43 24 4
gpt4 key购买 nike

Possible Duplicate:
how to get class instance of generics type T

模板的T在

JAXBContext jaxbContext = JAXBContext.newInstance(T.class);

无法编译 T.class ,是否需要反射以及如何编译?

    public void ConvertObjectToXML(String path, T bobject)
{
//Convert XML to Object
File file = new File(path);
JAXBContext jaxbContext = JAXBContext.newInstance(T.class);

Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
T customer2 = (T) jaxbUnmarshaller.unmarshal(file);
System.out.println(customer2);
}

最佳答案

由于 Java 处理泛型类型的方式,此代码无法工作:

public class Factory<T>{
public T create(){
return T.class.newInstance();
}
}

您需要将实际的泛型类型传递给构造函数(或任何其他方法):

public class Factory<T>
Class<T> c;
publict Factory(Class<T> c){
this.c=c;
}
public T create(){
return c.newInstance();
}
}

经典方法是从数组推断泛型类型,因为数组确实保存其类型:

public interface List<T>{
...
T[] toArray(T[] target);
..
}

这是因为实际运行时类型为 Factory<T>只是Factory ,因此运行时无法访问其泛型类型。

关于java - 如何用java编写T.class?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13083509/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com