2016-08-18 63 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; 
     } 
    } 
相关问题