Created
June 22, 2014 15:53
-
-
Save liweinan/568f1cbdd8b9188e17b3 to your computer and use it in GitHub Desktop.
ObjectFactory Demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import javax.xml.bind.JAXBContext; | |
import javax.xml.bind.JAXBElement; | |
import javax.xml.bind.Unmarshaller; | |
import javax.xml.bind.annotation.XmlElementDecl; | |
import javax.xml.bind.annotation.XmlRegistry; | |
import javax.xml.namespace.QName; | |
import java.io.ByteArrayInputStream; | |
import java.io.InputStream; | |
import java.nio.charset.StandardCharsets; | |
/** | |
* @author <a href="mailto:l.weinan@gmail.com">Weinan Li</a> | |
*/ | |
@XmlRegistry | |
public class ObjectFactory { | |
private static class Bar { | |
private int x; | |
public int getX() { | |
return x; | |
} | |
public void setX(int x) { | |
this.x = x; | |
} | |
} | |
@XmlElementDecl(name = "barbar") | |
public JAXBElement<Bar> createBar(Bar bar) { | |
return new JAXBElement<Bar>(new QName("barbar"), Bar.class, bar); | |
} | |
public static void main(String[] args) throws Exception { | |
Bar bar = new Bar(); | |
bar.setX(1); | |
JAXBContext ctx = JAXBContext.newInstance(ObjectFactory.class); | |
Unmarshaller um = ctx.createUnmarshaller(); | |
InputStream stream = new ByteArrayInputStream("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><barbar><x>1</x></barbar>\n".getBytes(StandardCharsets.UTF_8)); | |
JAXBElement<Bar> barElem = (JAXBElement<Bar>) um.unmarshal(stream); | |
System.out.println(barElem.getValue().getX()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment