Java Generics for unmarshall JAXB Object

Vel*_*Vel 3 java xml generics jaxb

我有以下代码将xml解组为Java对象.我想看看是否可以通过使用Java Generics而不是使用Object类型作为返回值来增强此代码.

protected static <T> Object unmarshall(String xml, Class<T> clazz)
        throws JAXBException {
    JAXBContext jc = JAXBContext.newInstance(clazz);
    Unmarshaller unmarshaller = jc.createUnmarshaller();
    Object obj = unmarshaller.unmarshal(new StringReader(xml));
    return obj;
}
Run Code Online (Sandbox Code Playgroud)

有什么建议.

Tho*_*sch 7

是的,您可以稍微增强您的代码:

protected static <T> T unmarshall(String xml, Class<T> clazz)
        throws JAXBException {
    JAXBContext jc = JAXBContext.newInstance(clazz);
    Unmarshaller unmarshaller = jc.createUnmarshaller();
    T obj = clazz.cast(unmarshaller.unmarshal(new StringReader(xml)));
    return obj;
}
Run Code Online (Sandbox Code Playgroud)

  • SuppressWarnings是一种快速而肮脏的解决方法,可以隐藏程序员的错误.为什么不使用[typesafe版本](http://docs.oracle.com/javase/8/docs/api/javax/xml/bind/Unmarshaller.html#unmarshal-javax.xml.transform.Source-java.lang .Class-)代替:`T obj = unmarshaller.unmarshal(new StreamSource(new StringReader(xml)),clazz).getValue();` (2认同)

k5_*_*k5_ 6

如果您不需要/不想重用 JAXBContext,则无需创建它。有一种方便的方法(几乎)具有您想要的方法签名。它抛出一个RuntimeException(许多人更喜欢那个)。

protected static <T> T unmarshall(String xml, Class<T> clazz) {
    return JAXB.unmarshal(new StringReader(xml), clazz);
}
Run Code Online (Sandbox Code Playgroud)

但是imo,直接使用该方法,无需包装器。

JAXBContext从长远来看,重用 a会使(取消)编组速度更快。另一个改进是clazz.cast()避免讨厌的未经检查的演员表

private static final ConcurrentMap<Class<?>, JAXBContext> CONTEXT = new ConcurrentHashMap<>();

protected static <T> T unmarshall(String xml, Class<T> clazz)
        throws JAXBException {
    JAXBContext context = CONTEXT.get(clazz);
    if (context == null){
        context = JAXBContext.newInstance(clazz);
        CONTEXT.putIfAbsent(clazz, context);
    }

    Unmarshaller unmarshaller = context.createUnmarshaller();
    Object obj = unmarshaller.unmarshal(new StringReader(xml));
    if (clazz.isInstance(obj)){
        return clazz.cast(obj);
    }
    throw new IllegalArgumentException("XML does not represent an instance of type:" + clazz.getName());
}
Run Code Online (Sandbox Code Playgroud)