Tarken
Tarken

Reputation: 2202

How to call constructor with nested generic in java

I got the following class:

public class Repository<T> extends ExternalRepository<Wrapper<T>> 
{
    public Repository(Class<Wrapper<T>> type, DB db) 
    {
        super(type, db);
    }
}

But I have no idea how to call the construtor since

new Repository(Wrapper<SomeClass>.class, dbInstance)

does not work. So what can I do? I can change the Repository class if necessary.

Upvotes: 0

Views: 123

Answers (2)

Rohit Jain
Rohit Jain

Reputation: 213263

You can't get the class instance for Wrapper<SomeClass> directly using .class literal. It is not allowed. You can only use it with raw type - Wrapper.class, or unbounded wildcard types - Wrapper<?>.class.

To get what you want, you've to use some type-casting here:

new Repository<SomeClass>((Class<Wrapper<SomeClass>>)(Class<?>)Wrapper.class, 
                           dbInstance)

This first cast a Class<Wrapper> to a Class<?>, which is an unbounded wildcard reference. And then that reference can be type-casted to Class<Wrapper<SomeClass>>.

Also, don't forget to give the type argument while creating an instance of your generic class.

Upvotes: 1

Andrei Nicusan
Andrei Nicusan

Reputation: 4623

Here's what you need:

new Repository(Wrapper.class, dbInstance);

There's only one class descriptor for each generic class, including Wrapper.

Upvotes: 0

Related Questions