如何在参数需求类中使用泛型

时间:2016-08-18 06:22:40

标签: generics jaxb

在我的示例中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 个答案:

答案 0 :(得分: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;
        }
    }