0

I have a method with an template parameter:

public CustomClass getData(Class<? extends InterfaceA> item) {  

} 

I have ended up with one case that this can be called with an item that can be an inner anonymous class that adheres to the class expected but how can I know when I got this object inside my method?
If I do if(item.equals(ConcreteA.class)) where ConcreteA is the usual class that works it fails.
Also if I use class name I need to use something like:
item.getName().equals(“com.a.b.Utils$1”);

How can I check the instance in this case?

2
  • You're missing the getClass() on item. I.e. if (item.equals.getClass()(ConcreteA.class)). Still, I don't understand your problem. Why is it important to check for class-equality? What do you want to achieve with this? Commented Jun 30, 2016 at 10:28
  • @TamasRev:I need to do something specific to that Commented Jun 30, 2016 at 19:19

1 Answer 1

1

You need to check whether the types are compatible, i.e., whether InterfaceA is a supertype of item:

boolean isValidType = InterfaceA.class.isAssignableFrom(item)

API Docs: https://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#isAssignableFrom(java.lang.Class)

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

2 Comments

If item is of type Class<? extends InterfaceA>, wouldn't isValidType always be true?
@AndyTuner: In theory, yes: at compile time, and assuming the code calling this method is generic. But there's no such guarantee at runtime (type erasure). Calls could also be using reflection... But there's a reason for the check needed by Jim.

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.