Unmarshal generates null field on generic with a List<T> field
I have a Web Service created in Java (1.6), with metro (2.0), using maven, under Tomcat 6. In all web methods the return type is a generic class:
public class WsResult<T> {
protected T result; // the actual result
protected Code requestState; // 0K, or some error code if needed
protected String message; // if error, instead of result, insert a message
}
For example:
public WsResult<OtherClass> someMethod(...);
public WsResult<Foo> someMet开发者_运维问答hod_2(...);
And in client:
MyServiceService service = new MyServiceService();
MyService port = service.getMyServicePort();
WsResult result = port.someMethod(...);
OtherClass oc = (OtherClass) result.getResult();
WsResult res = port.someMethod_2(...);
Foo o = (Foo) res.getResult();
In some web methods it is working.
But when the result is a class with have a List<? class>
attribute, it fails to unmarshal.
This project is part of a biggest one. So for test purposes I created a new one, simpler, just the project, with the same data model, and copy one of the web methods, in this case it worked, and after unmarshal, I had a result that i could cast to the expected type.
What could be happening?
EDIT:
The answer is a solution yes, but generates a getter for each type added to the field declaration. Is there a better way?
I'm not really sure if I fully understand your problem, but to me it seems you expect a little too much from JAXB here. Your WsResult
is generic in the unrestricted parameter T
, which means at runtime there's nothing left but an Object
reference for JAXB to play with.
What JAXB really needs to deal with such a situation is, loosely speaking, a hint on which class to instantiate to fill the result
field. To fill this in you should either
- create concrete subclasses of
WsResult
(like, following your example,class OtherClassResult extends WsResult<OtherClass>
-- when you throw theOtherClassResult
at JAXB, it will know thatresult
needs to be an instance ofOtherClass
and has a chance to act accordingly or - annotate the
result
field with@XmlElements
, like this:
@XmlElements({ @XmlElement(name = "text", type = String.class), // add more elems here @XmlElement(name = "other", type = OtherClass.class)}) protected Object result;
精彩评论