java - 生成java方法
问题描述
我有如下方法
public InstitutionsType toInstitutionPOJO(String xml) throws Exception {
InputStream stream = new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8));
JAXBContext jaxbContext = JAXBContext.newInstance(InstitutionsType.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLEventReader someSource = factory.createXMLEventReader(stream);
JAXBElement<InstitutionsType> userElement = jaxbUnmarshaller.unmarshal(someSource, InstitutionsType.class);
return userElement.getValue();
}
public ErrorType toErrorPOJO(String xml) throws Exception {
InputStream stream = new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8));
JAXBContext jaxbContext = JAXBContext.newInstance(ErrorType.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLEventReader someSource = factory.createXMLEventReader(stream);
JAXBElement<ErrorType> userElement = jaxbUnmarshaller.unmarshal(someSource, ErrorType.class);
return userElement.getValue();
}
我必须创建大约 14 种类似的方法,除了输出类型之外它们完全相同。我们可以把这个泛化吗?
解决方案
像这样的东西应该可以解决问题..
public <T> T toPOJO(String xml, Class<T> type) throws Exception {
InputStream stream = new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8));
JAXBContext jaxbContext = JAXBContext.newInstance(type);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLEventReader someSource = factory.createXMLEventReader(stream);
JAXBElement<T> userElement = jaxbUnmarshaller.unmarshal(someSource, type);
return userElement.getValue();
}
推荐阅读
- python - 计算线穿过两点的角度 - 如何正确缩放?
- powershell - 如何通过Powershell从具有属性(我自己自定义创建的列)的共享点文件夹中获取所有文件?
- apache-spark - 从一个数据帧生成多个输出,只读取一次数据
- android - Firebase 和本地化
- oracle - 对函数调用(堆栈帧)中的类型强制感到困惑
- sql - 加入倾斜关系时,有没有办法改进 PostgreSQL 估计?
- c - 在对 fgets 的不相关函数调用后清除字符数组?
- python-3.x - Tkinter 应用程序崩溃,同时单击不同的按钮
- memory - 汇编 - 为什么静态分析代码中的值会发生变化?
- java - 具有提供范围的库仍然存在于 jar 中