Get Java class name from QName

Suppose you have a QName that represents a type in a .xsd document. How can I find out the name of the class in which it will be disconnected?

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

This gets unmarshalled in com.domain.service.things.Customer .

Is there a way to do this without parsing the string representation of a QName?

Edit:

I have a specific .xsd that is used to create Java classes. I want to select one of these Java classes dynamically based on QName, which is passed as a String in an HTML form.

Edit2:

Since the names of these classes are automatically generated, somewhere there must be a method that generates their names from QName.

+4
source share
2 answers

You can use 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 classes of models:

A

 package example; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name="EH", namespace="http://www.example.com") public class A { } 

IN

 package example; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name="BEE", namespace="urn:example") public class B { } 

WITH

 package example; public class C { } 

Output

 class example.A 
+4
source
 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
source

Source: https://habr.com/ru/post/1340246/


All Articles