有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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 需要:

  1. ContentHandler
  2. 输出流
  3. XmlEventWriter
  4. 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) 个答案

  1. # 1 楼答案

    您不需要向方法中添加额外的泛型参数。只需传递一个javax。xml。使改变结果发送给封送员:

    private <U> void fun(U u, Result result) {
      JAXBContext context = JAXBContext.newInstance(u.getClass());
      Marshaller marshaller = context.createMarshaller();
      marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
      marshaller.marshal(u, result);
    }
    

    您可以使用StreamResult写入系统。输出或写入文件:

    fun(foo, new StreamResult(System.out));
    fun(foo, new StreamResult(file_pointer.openOutputStream()));