[英]Can we create different class instance using Java generics by passing class type as argument
我正在尝试从 xml 文件创建对象。 目前我正在提供要在方法签名中解析的 Class 类型。 例如,您在下面的代码中看到的 TestRequest。 因此,我无法使用相同的方法来创建另一种对象类型。 是否可以编写一个方法,可能使用泛型,通过将类类型作为参数传递来返回不同的类实例。
当前代码:
private static JAXBElement<TestRequest> createRequestObject(String xmlFile) {
JAXBElement<VerifyRequest> result;
try {
JAXBContext ctx = JAXBContext.newInstance(TestRequest.class);
Unmarshaller unmarshaller = ctx.createUnmarshaller();
String xmlString = loadFile(xmlFile);
result = unmarshaller.unmarshal(new StreamSource(new ByteArrayInputStream(xmlString.getBytes())), VerifyRequest.class);
} catch (JAXBException | IOException e) {
throw new RuntimeException(e);
}
return result;
}
期待类似的东西
private static <T> JAXBElement<T> createRequestObject(String xmlFile, Class objectType) {
private static <T> JAXBElement<T>
createRequestObject (String xmlFile, Class<T> type)
那应该就够了。
如果您调用createRequestObject(file, TestRequest.class)
,则T
被解析为TestRequest
,因此返回类型将为JAXBElement<TestRequest>
。 其他类型类似。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.