简体   繁体   English

JAXB通用XmlAdapter实现

[英]JAXB Generic XmlAdapter implementation

This question continues my previous thread : here 这个问题继续了我以前的话题: 这里

Now i want to use a generic XmlAdapter, because i need to apply the same work on differents type of value. 现在,我想使用通用的XmlAdapter,因为我需要将相同的工作应用于值的不同类型。 I can create one class per type, but that's not the purpose of my question, i want to make this generic. 我可以为每种类型创建一个类,但这不是我的问题的目的,我想使它通用。 So this is what i did : 所以这就是我所做的:

Generic Adapter Class 通用适配器类

public class GenericXMLAdapter<T> extends XmlAdapter<GenericXMLAdapter.AdaptedValue<T>, T>{
  public static class AdaptedValue<T> {
        @XmlAttribute
        public T code;
  }

  @Override
  public T unmarshal(AdaptedValue<T> v) throws Exception {
        return v.code;
  }

  @Override
  public AdaptedValue<T> marshal(T v) throws Exception {
        AdaptedValue<T> adaptedValue = new AdaptedValue<T>();
        adaptedValue.code = v;
        return adaptedValue;
  }

} }

My temporary class to generate the correct Adapter 我的临时类生成正确的适配器

public final class DefinedXMLAdapter {
      public static class BooleanAdapter extends GenericXMLAdapter<Boolean> {};
}

Example to marshall 编组的例子

  @XmlElement(name = "theBoolean")
  @XmlJavaTypeAdapter(DefinedXMLAdapter.BooleanAdapter.class)
  protected Boolean myBoolean = false;

When i execute my code, i get a weird error i can't understand : 当我执行代码时,出现一个我不明白的怪异错误:

Exception in thread "main" java.lang.NullPointerException
  at com.sun.xml.internal.bind.v2.runtime.reflect.TransducedAccessor.get(TransducedAccessor.java:154)
  ...

Can someone explains to me what's wrong with my code and how to resolve this issue ? 有人可以向我解释我的代码有什么问题以及如何解决此问题吗?

I finally managed to solve my problem by using MOXy as the JAXB implementation. 我最终设法通过使用MOXy作为JAXB实现来解决我的问题。 Thanks for your time, have a good day! 谢谢您的时间,祝您有美好的一天!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM