javagenericsektorp

Retrieve the .class attribute of a generic class


I am trying to extend the following class with constructor (from the Ektorp library):

public class CouchDbRepositorySupport<T extends CouchDbDocument> implements GenericRepository<T> {

...

protected CouchDbRepositorySupport(Class<T> type, CouchDbConnector db) {
...

}

Here's my implementation:

public class OrderRepository extends CouchDbRepositorySupport<Order<MenuItem>> {

    public OrderRepository(CouchDbConnector db) {
        super(Order<MenuItem>.class, db);

The problem is with the Order<MenuItem>.class part. The Java compiler tells me:

 Syntax error on token ">", void expected after this 

I tried with (Order<MenuItem>).class, Order.class and new Order<MenuItem>().getClass() with no better luck.

What can I do to retrieve the .class attribute of a generic class?


Solution

  • If you change your type to publish the inner type, you can get it this way:

    public class CouchDbRepositorySupport<C, T extends CouchDbRepositorySupport<C>> implements GenericRepository<T> {
    ...
    
        protected CouchDbRepositorySupport(Class<C> type, CouchDbConnector db) {
            ...
        }
    
    public class OrderRepository extends CouchDbRepositorySupport<MenuItem, Order<MenuItem>> {
    
        public OrderRepository(CouchDbConnector db) {
            super(MenuItem.class, db);
    

    You have a few choices about how you declare the parent class; this is just one example.

    Disclaimer: I did this by hand without an IDE, so there could be a few minor syntax issues with it, but the concept should work.