11

我使用 MOXy 作为 JAXB 实现,但不知何故,我想在某些管理屏幕上(动态)显示实现名称(例如 Moxy)和版本号。

如何从 JAXB 检索该信息?

干杯

4

2 回答 2

11

您可以执行以下操作来确定正在使用的 JAXB impl:

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");
        }
    }

}

您可以从其 Version 类中获取有关正在使用的 EclipseLink 版本的信息:

import org.eclipse.persistence.Version;

public class VersionDemo {

    public static void main(String[] args) {
        System.out.println(Version.getVersion());
    }
}
于 2011-01-24T15:17:30.100 回答
2

基于 Blaise Doughan 的回答,稍作修改(JUnit 测试)。请注意,Metro 实现的包似乎发生了变化(可能在 Java6u4 附近)。还是没有自检界面?伤心!

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);
    }

}
于 2017-09-04T13:43:05.843 回答