Testing which interfaces a class/interface implements?
I want to test which interfaces a class/interface is implementing.
So I have a basic interface Adapter
and some interfaces base on it (e.g. PermissionsAdapter
). Now I get a variable typed as Adapter
and now I want to get every interface based on Adapter
that this variable is implementing.
A simple implementation:
import java.util.LinkedList;
import java.util.List;
public class Main {
private interface A { }
private interface BA extends A { }
private interface CA extends A { }
private interface X {}
private class IB implements BA { }
private class IC implements CA { }
private class IBC implements BA, CA { }
private class ICX implements CA, X { }
private class IBCX implements BA, CA, X {}
public Main() {
this.test(new IB());
this.test(new IC());
this.test(new IBC());
this.test(new ICX());
this.test(new IBCX());
}
private void test(A a) {
List<Class<? extends A>> result = this.getAdapterInterfaces(a);
System.out.print(a.getClass().getSimpleName() + "{");
for (Class<? extends A> class1 : result) {
System.out.print(class1.getSimpleName() + ", ");
}
System.out.println("}");
}
@SuppressWarnings("unchecked")
public List<Class<? extends A>> getAdapterInterfaces(A adapter) {
List<Class<? extends A>> result = new LinkedList<Class<? extends A>>();
Class<?>[] interfaces = adapter.getClass().getInterfaces();
for (Class<?> clazz : interfaces) {
if (A.class.isInstance(clazz)) {
result.add((Class<? extends A>) clazz);
}
}
return result;
}
public static void main(String[] 开发者_C百科args) {
new Main();
}
}
Here is the Adapter
the interface A
and the PermissionsAdapter
for example BA
and CA
is another adapter. X
is only a sample interface, which the list shouldn't contain.
And the result:
IB{}
IC{}
IBC{}
ICX{}
IBCX{}
So it doesn't seem to work. Now where is my mistake in getAdapterInterfaces(A)
? I think it is the test, but how could I test, if a class is a specific class of A
?
Fabian
Your test A.class.isInstance(clazz)
is wrong. It tests whether the interface's class object is of your A
type, which it isn't (it is of type Class
, Object
, Serializable
, AnnotatedElement
, GenericDeclaration
and Type
(in 1.6), nothing more).
You want Class.isAssignableFrom
, I think. (But read the documentation.)
Also, you might need to recurse to the superclass and the interfaces, since there could be indirect implementations.
精彩评论