0

Given the path to a class file, how can I find out if it implements a certain interface?

I could use javap and parse the output, but there are probably more intelligent ways.

I do not want to parse the source code because it may not be available. I should also note that the path of the class file will be available only at runtime.

J Fabian Meier
  • 33,516
  • 10
  • 64
  • 142
  • Can't you load that class and use something like [this](http://stackoverflow.com/questions/6616055/get-all-derived-interfaces-of-a-class) to get all interfaces – TheLostMind Nov 18 '15 at 07:56
  • 1
    @ParkerHalo: not really a duplicate. here the question is about the class, there it was about parsing through source code itself – Stultuske Nov 18 '15 at 07:59
  • @VinodMadyalkar: that's overkill. for one specific interface, an instanceof check will do. – Stultuske Nov 18 '15 at 08:00
  • It is easier to use `isAssignableFrom` when you have two classes. http://stackoverflow.com/a/3949379/1651233 – BobTheBuilder Nov 18 '15 at 08:02
  • @Stultuske - Yes. Probably. `instanceof` would not be a bad idea here :) – TheLostMind Nov 18 '15 at 08:49

2 Answers2

0

If you need to check it from the command line then javap is an option.

If you need to check it from within the code this should work

interface MyInterface {
    ...
}
try {
    URL classUrl;
    classUrl = new URL(<path to the dir containg the .class file>); 

    URL[] classUrls = { classUrl };
    URLClassLoader ucl = new URLClassLoader(classUrls);

    Class clazz = ucl.loadClass(<your class name>); 
    if (MyInterface.class.isInstance(clazz.newInstance())){
        ...
    }
}
catch (Exception e){ System.out.println(e);}
-1

Let us assume Class A implements Interface B

To check that you can use InstanceOf operator

A a = new A();
if(a instanceof B)  // here a is refernce variable holding object of class A
{
//do your thing
}

EDIT

Class clazz = (Class) Class.forName("Your class name");
for (Class c : clazz.getClass().getInterfaces()) {
   String name=c.getName());
   if(name.equals("org.apache.SomethingInterface"))
    {
     now u know u have it implemented
    }
}
Kumar Saurabh
  • 2,297
  • 5
  • 29
  • 43