2016-08-18 66 views
0

在我的示例JAXBContext.newInstance(T)需要參數類和此泛型解決方案不起作用。如何在參數中使用泛型需要類

public class SerializationUtilJaxb<T> { 

    public String serialize(T jaxbObject) { 
     StringWriter stringWriter = new StringWriter(); 
     try { 
      JAXBContext jaxbContext = JAXBContext.newInstance(T); 
      Marshaller objectMarshaller = jaxbContext.createMarshaller(); 
      objectMarshaller.marshal(jaxbObject, stringWriter); 
      return stringWriter.toString(); 
     } catch (JAXBException e) { 
      throw new RuntimeException(e); 
     } 
    } 
} 

請問爲什麼?什麼是正確的解決方案與泛型?

回答

1

使用無界通配符?改爲。

public static void SerializationUtilJaxb(Class<?> rootClass, Object rootObj) throws JAXBException, IOException{ 

     try{ 
      StringWriter stringWriter = new StringWriter(); 
      JAXBContext context = JAXBContext.newInstance(rootClass); 
      Marshaller m = context.createMarshaller();  
      m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); 
      m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); 
      m.marshal(rootObj, stringwriter); 
     } 
     catch(Exception e){ 
      // System.out.println (e.getMessage); 
      throw e; 
     } 
    } 
相關問題