开发者

Can JAXB store the class name in the XML so that the the deserialize code doesn't need knowledge of the class?

开发者 https://www.devze.com 2023-02-01 22:07 出处:网络
It seems the standard approach for deserializing JAXB XML is to specify the package name when creating the context.Then, JAXB looks up the class based on the root element:

It seems the standard approach for deserializing JAXB XML is to specify the package name when creating the context. Then, JAXB looks up the class based on the root element:

JAXBContext jc = JAXBContext.newInstance("com.foo");
Unmarshaller u = jc.createUnmarshaller();
Object o = u.unmarshal(new StringReader("<?xml version="1.0" encoding="UTF-8"     standalone="yes"?><MyJaxb>..."));

I'm looking for a more flexible approach where I don't have to specify the package name and could still deserialize any object. This would be as simple as JAXB storing the package in the XML, but I can't 开发者_JAVA技巧seem to find out how to do this. I can write the code to do it myself but that would be unpleasant. It would like JAXB to do it, if possible. BTW, I am not using schemas, just Annotations and marshal/unmarshal. Any ideas?


Actually you can not deserialize "any" object with pure JAXB. You have to specify either packages (where ObjectFactory.class will be sought) or list of classes like JAXBContext.newInstance(Class1.class, Class2.class, Class3.class); That's how jaxb works, it's a part of agreement. If your tasks are wider that that, e.g. building java classes from arbitrary xml data structure - it's also possible, but you have to be a bit more concrete - what do you mean under "more flexible approach".


You should be able to add more than one package when you get the instance of the jaxbcontext object. You can add as many packages as you want like below.

JAXBContext jc = JAXBContext.newInstance("com.foo.package1:com.foo.package2" ); 

however, I am not sure how you are gonna use it if you deserialize it into an Object instance? Are you not gonna use what you have just deserialized?

Also Unmarshaller is not a thread safe class if your application is a multithreaded one.

0

精彩评论

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

关注公众号