1

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?.

3
  • 1
    Try Class<? extends Identifiable>. Commented Jan 12, 2017 at 8:55
  • I believe type erasure is the reason your first attempt is failing. But can you explain to us why you think you need to pass class type information into your method? Commented Jan 12, 2017 at 8:55
  • u are right. Its working. thanks a lot. Commented Jan 12, 2017 at 9:08

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.