如何在 JAXB 中序列化 Exception 子类? [英] How do you serialize an Exception subclass in JAXB?

查看:39
本文介绍了如何在 JAXB 中序列化 Exception 子类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何序列化 Exception 的子类?

How do you serialize a subclass of Exception?

这是我的例外:

@XmlType
public static class ValidationFault extends Exception {
    public ValidationFault() {

    }
}

我已经尝试过使用 @XmlTransient 和 @XmlAccessorType 的各种变体,但 JAXB 不断尝试序列化 getStackTrace/setStackTrace 对,但这是无法完成的.

I have tried all sorts of variations on using @XmlTransient and @XmlAccessorType, but JAXB continually tries to serialize the getStackTrace/setStackTrace pair, which can't be done.

如何告诉 JAXB 忽略父级上的所有字段?

How do I tell JAXB to ignore all the fields on the parent?

推荐答案

我通过以下信息解决了这个问题:http://forums.java.net/jive/thread.jspa?messageID=256122

I solved this with the information at: http://forums.java.net/jive/thread.jspa?messageID=256122

您需要使用以下配置初始化您的 JAXBContext(其中 jaxbObj 是要序列化的对象):

You need to initialize your JAXBContext with the following config (where jaxbObj is the object to serialize):

Map<String, Object> jaxbConfig = new HashMap<String, Object>(); 
// initialize our custom reader
TransientAnnotationReader reader = new TransientAnnotationReader();
try {
    reader.addTransientField(Throwable.class.getDeclaredField("stackTrace"));
    reader.addTransientMethod(Throwable.class.getDeclaredMethod("getStackTrace"));
} catch (SecurityException e) {
    throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
    throw new RuntimeException(e);
} catch (NoSuchFieldException e) {
    throw new RuntimeException(e);
}
jaxbConfig.put(JAXBRIContext.ANNOTATION_READER, reader); 

JAXBContext jc = JAXBContext.newInstance(new Class[] {jaxbObj.getClass()},jaxbConfig);

这篇关于如何在 JAXB 中序列化 Exception 子类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆