You should use Class#isAssignableFrom(Class<?> cls)
method here:
Class<?> classObj = MePOJO.class;
System.out.println(IPOJO.class.isAssignableFrom(classObj));
Output:
true
Pregunta
here we go,
I have an marker interface :
interface IPOJO {
}
And then i have a class implementing this interface :
class MePOJO implements IPOJO {
}
Now suppose i have a class object
holding reference of class MePOJO :
Class<MePOJO> classObj = MePOJO.class;
So how can i determine if MePOJO
class implements IPOJO
just by using classObj
?
Solución
You should use Class#isAssignableFrom(Class<?> cls)
method here:
Class<?> classObj = MePOJO.class;
System.out.println(IPOJO.class.isAssignableFrom(classObj));
Output:
true
Otros consejos
There are several approaches for this.
Either by using the Class type of the object you've created and retrieve the list with all the interfaces that it implements.
MePOJO test = new MePOJO();
Class[] interfaces = test.getClass().getInterfaces();
for (Class c : interfaces) {
if ("IPOJO".equals(c.getSimpleName()) {
System.out.println("test implements IPOJO");
}
}
Or using the Class#isAssignableFrom(Class clazz) method:
Class<?> clazz = MePOJO.class;
System.out.println(IPOJO.class.isAssignableFrom(clazz));
The correct way to do this is not with marker interfaces at all but with annotations:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public static @interface Pojo {
}
@Pojo
public static class MePojo {
}
public static void main(String[] args) throws Exception {
System.out.println(MePojo.class.isAnnotationPresent(Pojo.class));
}
Output:
true
This way you don't pollute the namespace with marker interfaces.
Check with the keyword instanceOf
if(classObj instanceOf IPOJO ){
}
The instanceof operator evaluates to true if and only if the runtime type of the object is assignment compatible with the class or interface.
Use method isInstance from Class :
if (classObj.isInstance(myObj)){
...
}
http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html
There are also class members that allow you to get the names of the super class of the object. http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html