Skip to content

Instantly share code, notes, and snippets.

@RaffaeleSgarro
Last active December 14, 2015 22:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RaffaeleSgarro/a94254e8a4fbd8a09ebe to your computer and use it in GitHub Desktop.
Save RaffaeleSgarro/a94254e8a4fbd8a09ebe to your computer and use it in GitHub Desktop.
package stackoverflow.generics;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.Response;
public class JaxRs {
public static void main(String[] args) {
System.out.println(new UserResource().findAll());
}
static class UserModel {
String name;
UserModel(String name) {
this.name = name;
}
}
static class UserResource extends Resource<UserModel> {
@Override
public List<UserModel> getAll() {
List<UserModel> ret = new ArrayList<UserModel>();
ret.add(new UserModel("Foo"));
ret.add(new UserModel("Bar"));
ret.add(new UserModel("Baz"));
return ret;
}
}
static abstract class Resource<T> {
public Type getType() {
Type type = ((ParameterizedType) getClass().getGenericSuperclass())
.getActualTypeArguments()[0];
return new ListOfSomething(type);
}
public Response findAll() {
List<T> data = getAll();
return Response.ok(new GenericEntity<List<T>>(data, getType())).build();
}
public abstract List<T> getAll();
}
static class ListOfSomething implements ParameterizedType {
ListOfSomething(Type type) {
this.type = type;
}
Type type;
@Override
public Type[] getActualTypeArguments() {
return new Type[] { type };
}
@Override
public Type getRawType() {
return List.class;
}
@Override
public Type getOwnerType() {
return JaxRs.class;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment