Kaushi
Kaushi

Reputation: 198

Java Generics - Class<Interface>

I have created an interface called Identifier. And a class which implements Identifier interface is MasterEntity bean like below.

public class MasterEntity implements Identifier{

}

In DAO method, I wrote a method like below method signature.

public Identifier getEntity(Class<Identifier> classInstance){

}

Now from Service I want to call the method like below.

dao.getEntity(MasterEntity.class);

But am getting compilation error saying -

The method getEntity(Class<Identifiable>) in the type ServiceAccessObject 
is not applicable for the arguments (Class<MasterEntity>)

I know if I use like below it will work.

public Identifier getEntity(Class classInstance){

But by specifying the Class of type Identifiable, how it can be done?.

Upvotes: 1

Views: 62

Answers (1)

bsiamionau
bsiamionau

Reputation: 8229

Change DAO method signature to

public Identifier getEntity(Class<? extends Identifier> classInstance)

By declaring method as you described above you specify that the only applicable argument is Identifier.class itself. To be able to accept Identifier.class implementations, you should define generic type bounds.

List<? extends Shape> is an example of a bounded wildcard. The ? stands for an unknown type, just like the wildcards we saw earlier. However, in this case, we know that this unknown type is in fact a subtype of Shape. (Note: It could be Shape itself, or some subclass; it need not literally extend Shape.) We say that Shape is the upper bound of the wildcard.

Also you can take a look at this answer: https://stackoverflow.com/a/897973/1782379

Upvotes: 2

Related Questions