Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 519
jd. Avatar asked May 15 '12 20:05

jd.


2 Answers

The correct syntax would be:

Order.class

In Java, Order<MenuItem>.class and Order.class are the same class at runtime, the generic type information (the <MenuItem> type parameter) is lost at runtime because of type erasure - a severe limitation of Java's generic type system.

like image 189
Óscar López Avatar answered Oct 16 '22 00:10

Óscar López


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.

like image 45
Bohemian Avatar answered Oct 16 '22 02:10

Bohemian