给定类文件的路径,如何确定它是否实现了某个接口?
我可以使用 javap 并解析输出,但可能有更智能的方法。
我不想解析源代码,因为它可能不可用。我还应该注意,类文件的路径仅在运行时可用。
如果您需要从命令行检查它,那么 javap 是一个选项。
如果您需要从代码中检查它,这应该可以工作
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);}
让我们假设 A 类实现了接口 B
检查您是否可以使用 InstanceOf 运算符
A a = new A();
if(a instanceof B) // here a is refernce variable holding object of class A
{
//do your thing
}
编辑
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
}
}