How to know what JAXB implementation is used?

跟風遠走 提交于 2020-01-01 04:34:08

问题


I am using MOXy as JAXB Implementation but somehow I would like to show the Implementation Name (e.g. Moxy) and the version number on some admin screen (dynamically).

How can I retrieve that info from JAXB?

Cheers


回答1:


You could do something like the following to figure out the JAXB impl being used:

import javax.xml.bind.JAXBContext;

public class Demo {

    private static final String MOXY_JAXB_CONTEXT = "org.eclipse.persistence.jaxb.JAXBContext";
    private static final String METRO_JAXB_CONTEXT = "com.sun.xml.bind.v2.runtime.JAXBContextImpl";

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Root.class);

        String jaxbContextImpl = jc.getClass().getName();
        if(MOXY_JAXB_CONTEXT.equals(jaxbContextImpl)) {
            System.out.println("EclipseLink MOXy");
        } else if(METRO_JAXB_CONTEXT.equals(jaxbContextImpl)) {
            System.out.println("Metro");
        } else {
            System.out.println("Other");
        }
    }

}

You can get information about the EclipseLink version being used from it's Version class:

import org.eclipse.persistence.Version;

public class VersionDemo {

    public static void main(String[] args) {
        System.out.println(Version.getVersion());
    }
}



回答2:


Based on Blaise Doughan's answer, a slight modification (JUnit test). Note that the package of the Metro implementation seems to have changed (maybe around Java6u4). There still is no self-inspection interface? SAD!

import org.junit.Test;

public class JaxbVersion {

    @Test
    public void printJaxbInformation() throws JAXBException {
        String MOXY = "org.eclipse.persistence.jaxb";
        String METRO_EARLY = "com.sun.xml.bind.v2";
        String METRO_LATE = "com.sun.xml.internal.bind.v2"; // since JDK 6u4 (?)
        String CAMEL = "org.apache.camel.converter.jaxb";       
        Class<?> clazz = SomeJaxbGeneratedClass.class;
        // http://docs.oracle.com/javaee/7/api/javax/xml/bind/JAXBContext.html
        JAXBContext jc = JAXBContext.newInstance(clazz); 
        String jcClassName = jc.getClass().getName();
        String res;
        if (jcClassName.startsWith(MOXY)) {
            res = "EclipseLink MOXy";
        } else if (jcClassName.startsWith(METRO_EARLY) || jcClassName.startsWith(METRO_LATE)) {
            res = "Oracle Metro";
        } else if (jcClassName.startsWith(CAMEL)) {
            res = "Apache Camel";
        } else {
            res = "Unknown";
        }
        res = res + "(" + jcClassName + ")";        
        System.out.println(res);
    }

}


来源:https://stackoverflow.com/questions/4781958/how-to-know-what-jaxb-implementation-is-used

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!