12

I'm trying to use reflection to determine whether a passed-in class implements an IsWdidget interface:

public boolean isAWidget(Class<?> clzz) {
    Class<?> runtimeClass = ClassLoader.getSystemClassLoader().loadClass(clzz.getName());
    Class<?>[] impls = runtimeClass.getInterfaces();
    for(Class<?> clz : impls)
        if(clz.getName().equals(IsWidget.class.getName()))
            return true;

    return false;
}

Is this the best/most effecient way of determining this? I also see a IsWidget.class.isAssignableFrom(Class<?>) method...

4 Answers4

14

I would use the isAssignableFrom method to determine if IsWidget is a superinterface:

return IsWidget.class.isAssignableFrom(clzz);

To quote from the linked Javadoc above:

Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter.

rgettman
  • 176,041
  • 30
  • 275
  • 357
1

1) this makes no sense

  Class<?> runtimeClass = ClassLoader.getSystemClassLoader().loadClass(clzz.getName());

try this with any class

    Class<?> runtimeClass = ClassLoader.getSystemClassLoader().loadClass(clzz.getName());
    System.out.println(runtimeClass == clzz);

you will get

true

so if you remove this line and work directly with clzz it's already more efficient

2) try this

class X extends Thread {
}

public static void main(String[] args) throws ClassNotFoundException {
    System.out.print(Arrays.toString(X.class.getInterfaces()));
}

you will get

[]

this is similar to what your func is doing, but in fact X implements Runnable

3) and this is really efficient one-line solution to check if a class implements an interface

    System.out.print(Runnable.class.isAssignableFrom(X.class));

output

true
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
1

You can use the getInterfaces() method if you are having a Class object.

    Class c[] = clzz.getInterfaces();   
    if(Arrays.asList(c).contains(IsWidget.class))
    {
        return true;
    }

The getInterfaces method gives you an array of Class representing the interfaces. Or you could also use isAssignableFrom method as follows:

IsWidget.class.isAssignableFrom(clzz);

If you have an Object you can use the instanceof method.

Rahul Bobhate
  • 4,892
  • 3
  • 25
  • 48
0

If that works, it should be fine. You could also try calling the cast method of the Class class and do a try and catch.

nrubin29
  • 1,522
  • 5
  • 25
  • 53
  • This does work, but it really abuses the point of using a try/catch block. Plus the thrown exception will make the call more expensive than it has to be (though I'm not sure how much more efficient it would be to use reflection to determine the implementing interface) – codewario May 03 '13 at 17:12