java将非泛型方法转换为泛型方法
我有以下方法:
private <U> void fun(U u) throws JAXBException {
JAXBContext context = JAXBContext.newInstance(u.getClass());
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(u, System.out);
}
方法接受不同类型的参数。见here 需要:
- ContentHandler
- 输出流
- XmlEventWriter
- XMLStreamWriter等
如何修改上述方法,使我可以在函数参数中传递编组的目标,而不是System.out
例如,我想调用如下方法:
objToXml(obj1,System.out);
outToXml(obj1,file_pointer);
同样地
我尝试使用fun(obj1,PrintStream.class,System.out)
跟踪,但没有成功:
private <T, U, V> void fun(T t, Class<U> u, V v) throws JAXBException {
JAXBContext context = JAXBContext.newInstance(t.getClass());
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(t, (U) v);
}
# 1 楼答案
您不需要向方法中添加额外的泛型参数。只需传递一个javax。xml。使改变结果发送给封送员:
您可以使用StreamResult写入系统。输出或写入文件: