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) {
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.