用户登录
用户注册

分享至

如何在 JAXB 中序列化 Exception 子类?

  • 作者: 嗫?暁雲?
  • 来源: 51数据库
  • 2022-11-30

问题描述

如何序列化 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);
软件
前端设计
程序设计
Java相关