2012-08-09 39 views
0

我有以下方法:转换非通用方法通用方法

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. 的OutputStream
  3. XMLEventWriter的
  4. XMLStreamWriter等

如何修改上述方法,使得代替System.out,我可以通过目的地在函数参数中进行编组。

例如,我想调用如下方法:

objToXml(obj1,System.out); 
outToXml(obj1,file_pointer); 

同样。

我试着用fun(obj1,PrintStream.class,System.out)以下,但它是unsuccessfull:

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

类型'U'在第一个代码完全没有必要;你可以使用'Object' – newacct 2012-08-09 19:23:43

回答

3

你并不需要添加额外的通用参数,你的方法。一个简单的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())); 
+0

它可以用于控制台和文件,但其他的呢?请参阅更新。 – 2012-08-09 10:05:39

+0

那么,你需要什么?你可以用Result来做的事情非常广泛:你可以写入Streams/Writers和各种XML API(DOM,SAX,StAX)。如果这还不够,你总是可以重载你的'fun'方法来使用其他Marshaller.marshal实现。 – 2012-08-09 10:41:42