-
-
Save RaffaeleSgarro/a94254e8a4fbd8a09ebe to your computer and use it in GitHub Desktop.
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
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