0

I'm trying to write a generic REST endpoint for a Jersey application I'm developing with around 30-40 different entities. I was hoping I could do something like the following:

public interface RestResource<T extends Entity> {

    @GET
    @Path("/{id}")
    public Response getOne(@PathParam("id") Long id);

    @GET
    List<T> getAll();

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    T create(T model);

    @PUT
    boolean update(T model);

    @DELETE
    @Path("/{id}")
    boolean delete(@PathParam("id") Long id);

}

Then I was expecting I could have a main resource calling the sub resources defined like:

@Path("/api/")
public class MainResource {

    @Path("/entity1")
    public RestResource<Entity1> getEntity1Resource(){
        return new RestResource<Entity1>();
    }

    @Path("/entity2")
    public RestResource<Entity2> getEntity2Resource(){
        return new RestResource<Entity2>();
    }

}

Due to generics type erasure I'm really struggling to make this feasible, and it almost seems easier at this point to make a new class that will inherit the generic implementation like the following:

public class Entity1Resource extends AbstractRestResource<Entity1>{ }

Instead of having a bunch of useless classes that just inherit the generic resource like I've shown above, is there a tidy way of using the generic resource directly?

cmwarre
  • 11
  • 2
  • [Check this out](https://stackoverflow.com/a/43885147/2587435). If you add a dao/repository layer, it makes it easier. – Paul Samsotha Dec 15 '20 at 01:58
  • thanks @PaulSamsotha. I think that's actually what I've done. I've just edited my question to make it a bit clearer... Is there a way to directly use a generic resource as an endpoint without creating subclasses that inherit it? – cmwarre Dec 15 '20 at 15:39
  • How are your subclasses useless why you still need to add sub-resources? – Paul Samsotha Dec 15 '20 at 19:33

0 Answers0