Interfaces and reflection

How can I use reflection to verify if a (instance of a)class implements a certain interface? Suppose that the interface is java.rmi.Remote, so it has no fields, no methods. Thanks.
[194 byte] By [raduh] at [2007-9-26 1:20:01]
# 1
Yes. Take a look at the java.lang.Class.isInstance and java.lang.Class.isAssignableFrom methods.
schapel at 2007-6-29 0:53:29 > top of Java-index,Core,Core APIs...
# 2

If you're testing an instance against a known interface, it's dead easy: boolean yesItDoes = (obj instanceof MyInterface) ;

Doing so programmatically or against a class is a bit more involved: import java.lang.reflect.* ;

public class IFTest {

/** tests if an object implements an interface programmatically */

static boolean implementsInterface(Object anObj, Class anInterface) {

return (anInterface.isInstance(anObj)) ;

}

/** tests if a class implements an interface */

static boolean implementsInterface(Class aClass, Class anInterface) {

Class[] interfaces = aClass.getInterfaces() ;

for (int j=interfaces.length-1; j>=0; j--) {

if (anInterface.equals(interfaces[j])) {

return true ;

}

}

return false ;

}

}

Hope this gives you some ideas.

DragonMan at 2007-6-29 0:53:29 > top of Java-index,Core,Core APIs...
# 3
Duh.. I forgot about about isAssignableFrom() -- replace the body of the second method with... return (anInterface.isInstance(aClass)) ;
DragonMan at 2007-6-29 0:53:29 > top of Java-index,Core,Core APIs...