How to determine if a Java Class implements a part

2019-04-20 06:52发布

问题:

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...

回答1:

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.



回答2:

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


回答3:

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.



回答4:

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.