英文:
Can we create different class instance using Java generics by passing class type as argument
问题
以下是您想要的翻译内容:
private static <T> JAXBElement<T> createRequestObject(String xmlFile, Class<T> objectType) {
JAXBElement<T> result;
try {
JAXBContext ctx = JAXBContext.newInstance(objectType);
Unmarshaller unmarshaller = ctx.createUnmarshaller();
String xmlString = loadFile(xmlFile);
result = unmarshaller.unmarshal(new StreamSource(new ByteArrayInputStream(xmlString.getBytes())), objectType);
} catch (JAXBException | IOException e) {
throw new RuntimeException(e);
}
return result;
}
英文:
I am trying to create object from a xml file. Currently I am providing the Class type to be parsed in the method signature. For instance TestRequest as you see in the below code. Due to this I cannot use the same method to create another object type. Is it possible to write a method, probably using generics, to return different class instance by passing class type as parameter.
Current Code:
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;
}
Expecting something like
private static <T> JAXBElement<T> createRequestObject(String xmlFile, Class objectType) {
答案1
得分: 3
private static <T> JAXBElement<T>
createRequestObject(String xmlFile, Class<T> type)
That should be enough.
If you call createRequestObject(file, TestRequest.class)
, T
is resolved to be TestRequest
, and thus the return type would be JAXBElement<TestRequest>
. Similar for other types.
英文:
private static <T> JAXBElement<T>
createRequestObject (String xmlFile, Class<T> type)
That should be enough.
If you call createRequestObject(file, TestRequest.class)
, T
is resolved to be TestRequest
and thus the return type would be JAXBElement<TestRequest>
. Similar for other types.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论