On Mar 30, 2009, at 6:12 PM, Jaka JanĨar wrote:
> Is this problem solvable without modification of Jersey? You said
> that you gave up on generic Response because of the builder pattern.
> I don't mind not using ResponseBuilder. Doing "return new
> MyResponse(code, headers, entity);" is acceptable to me.
>
> All I can think of is doing reflection of type within my resource
> methods and passing that to MyResource. Or, alternatively, passing
> the Method to MyResponse and then doing the reflection there. But
> this is all very ugly.
Try doing something like the following:
public class MyResponse<T> extends javax.ws.rs.core.Response {
Type t;
T e;
MyResponse(T t) {
t = getSuperclassTypeParameter(getClass());
}
Object getEntity() {
return new GenericEntity(e, t);
}
// This code is copied from the implementation of GenericEntity
private static Type getSuperclassTypeParameter(Class<?>
subclass) {
Type superclass = subclass.getGenericSuperclass();
if (!(superclass instanceof ParameterizedType)) {
throw new RuntimeException("Missing type parameter.");
}
ParameterizedType parameterized = (ParameterizedType)
superclass;
return parameterized.getActualTypeArguments()[0];
}
...
}
It requires that you create an anonymous class e.g.:
@GET
public MyResponse<Bean> get() {
Bean b =
return new MyResponse<Bean>(b) {};
}
Paul.