Java 怎么查找指定JAXB属性的类型适配器

2019年7月21日19:57:33Java 怎么查找指定JAXB属性的类型适配器已关闭评论 464 1261字阅读4分12秒

1.简介

Java 怎么查找指定JAXB属性的类型适配器?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */



import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapters;

import java.beans.PropertyDescriptor;

public class Main {
    
     
    public static XmlJavaTypeAdapter findTypeAdapter(
            PropertyDescriptor jaxbProperty) {
        XmlJavaTypeAdapter adapterInfo = null;

        if (jaxbProperty.getReadMethod() != null) {
            adapterInfo = jaxbProperty.getReadMethod().getAnnotation(
                    XmlJavaTypeAdapter.class);
        }

        if ((adapterInfo == null)
                && (jaxbProperty.getWriteMethod() != null)) {
            adapterInfo = jaxbProperty.getWriteMethod().getAnnotation(
                    XmlJavaTypeAdapter.class);
        }

        if (adapterInfo == null) {
            Package pckg = jaxbProperty.getReadMethod().getDeclaringClass()
                    .getPackage();
            Class<?> returnType = jaxbProperty.getReadMethod()
                    .getReturnType();

            XmlJavaTypeAdapter possibleAdapterInfo = pckg
                    .getAnnotation(XmlJavaTypeAdapter.class);
            if ((possibleAdapterInfo != null)
                    && (returnType.equals(possibleAdapterInfo.type()))) {
                adapterInfo = possibleAdapterInfo;
            } else if (pckg.isAnnotationPresent(XmlJavaTypeAdapters.class)) {
                XmlJavaTypeAdapters adapters = pckg
                        .getAnnotation(XmlJavaTypeAdapters.class);
                for (XmlJavaTypeAdapter possibility : adapters.value()) {
                    if (returnType.equals(possibility.type())) {
                        adapterInfo = possibility;
                    }
                }
            }
        }

        return adapterInfo;
    }
}

 
继续阅读
编程十万个怎么办