开发者

Obtain Java Class name from QName

开发者 https://www.devze.com 2023-02-12 00:03 出处:网络
Suppose you have a QName that represents a type in an .xsd document.How can I find out the name of the class that it would unmarshal into?

Suppose you have a QName that represents a type in an .xsd document. How can I find out the name of the class that it would unmarshal into?

For example, I've got a QName: {http://www.domain.com/service/things.xsd}customer

This gets unmarshalled into a com.domain.service.things.Customer.

Is there a way I can do this without parsing the QName string representation?

Edit:

I've got a some .xsd's defined that are being used to create Java classes. I want to select one of these Java classes dynamically based on a QName that is being passed in as a String on an HTML form.

Edit2:

Since these classes' names are being automatically generated, somewhere there must be a method that generates their开发者_高级运维 names from a QName.


You could leverage the JAXBInstropector and do the following:

package example;

import java.util.HashMap;
import java.util.Map;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBIntrospector;
import javax.xml.namespace.QName;

public class Demo {

    public static void main(String[] args) throws Exception {
        Class[] classes = new Class[3];
        classes[0] = A.class;
        classes[1] = B.class;
        classes[2] = C.class;

        JAXBContext jc = JAXBContext.newInstance(classes);

        JAXBIntrospector ji = jc.createJAXBIntrospector();
        Map<QName, Class> classByQName = new HashMap<QName, Class>(classes.length);
        for(Class clazz : classes) {
            QName qName = ji.getElementName(clazz.newInstance());
            if(null != qName) {
                classByQName.put(qName, clazz);
            }
        }

        QName qName = new QName("http://www.example.com", "EH");
        System.out.println(classByQName.get(qName));
    }

}

The following are the model classes:

A

package example;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="EH", namespace="http://www.example.com")
public class A {
}

B

package example;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="BEE", namespace="urn:example")
public class B {
}

C

package example;

public class C {
}

Output

class example.A


private static String getClassName(final QName qName) {
    final String clazz = WordUtils.capitalize(qName.getLocalPart());
    final String ns = qName.getNamespaceURI();

    String s = ns.replace("http://", "");
    s = s.replace("www.", "");
    s = s.replace(".xsd", "");
    s = s.replace("/", ".");
    final String tld = s.split(".")[1];
    s = s.replace("." + tld, "");

    return tld + "." + s + "." + clazz;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消