2

Given

String className = "com.example.MyClass";

How would I be able to check if this class implements a specific interface?

I've tried

Class myClass = Class.forName(className);
if (myClass instanceof MyInterface) {}

and

if (myClass.isInstance(MyInterface.class)) {}

but neither work - obviously the Class object does not inherit MyInterface

What is the proper way to check if a class implements an interface only given the class name?

  • Try out the full accepted answer in the duplicate link, and if you still can't get it to work, drop a comment, and someone can reopen your question. – Tim Biegeleisen Sep 07 '18 at 02:31
  • @TimBiegeleisen I disagree - the link provided shows how to load a class but not check its super type. Are you telling me i need to load a new instance of the class before I can check its super? – Alex Plouff Sep 07 '18 at 02:34
  • Yes, I'm assuming this. AFAIK `instanceof` checks whether an _object_ is an instance of another class. You never created an object, which is why I said to try the accepted answer exactly, and if it still doesn't work, then drop a note. – Tim Biegeleisen Sep 07 '18 at 02:35
  • Ah, this makes sense now - I was hoping there was a way of doing this without having to load a new instance of the implementation. Thanks for clarifying – Alex Plouff Sep 07 '18 at 02:38
  • I un-duped your answer, I was going to answer, but felt I would just be copying someone else's answer and changing maybe 1-2 lines. But hopefully your problem is solved now. – Tim Biegeleisen Sep 07 '18 at 02:38
  • Lol, now that I think about it - you should probably leave it duped as that answer does contain the key. I don't think this is possible w/o loading the implementation class; otherwise you're just left with a Class object Maybe I could achieve something similar through generics? Class extends MyInterface> myClass = Class.forName(myClass); ?? – Alex Plouff Sep 07 '18 at 02:58

1 Answers1

1

You can do that with Class.isAssignableFrom(Class):

if (MyInterface.class.isAssignableFrom(myClass)) {
  ...
}
Lolo
  • 4,277
  • 2
  • 25
  • 24