簡體   English   中英

將非泛型方法轉換為泛型方法

[英]Convert non-generic method to generic method

我有以下方法:

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);
    }

marshal()方法采用不同類型的參數。 請參閱此處需要:

  1. 內容處理程序
  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);
    }

您無需在方法中添加其他通用參數。 只需將javax.xml.transform.Result傳遞給編組器即可:

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寫入System.out或文件:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM