How to check instanceof on an argument that is a Class object?

左心房为你撑大大i 提交于 2020-01-03 10:15:07

问题


I'm trying to build a generic class loader. I need to check classes that I load against a method argument to determine if they are of the same class.

The code mostly explains what I'm trying to do.

private static LinkedList<Object> loadObjectsInDirectory(Class class0, File dir) throws ClassNotFoundException {

            LinkedList<Feature> objects = new LinkedList<Object>();

            ClassLoader cl = new GenericClassLoader();

            for(String s : dir.list()) {
                Class class1 = cl.loadClass(s);
                try {
                    Object x = class1.newInstance();
                    if (x instanceof (!!! class0 !!!) ) {
                        objects.add(x);
                    }
                } catch (InstantiationException ex) {
                } catch (IllegalAccessException ex) {
                }

            }

            return objects;

        }

How is this achieved?


回答1:


Looks like you need the isAssignableFrom method

if (kelass.isAssignableFrom(klass)) {
   objects.add(x);
}

JavaDoc

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. It returns true if so; otherwise it returns false. If this Class object represents a primitive type, this method returns true if the specified Class parameter is exactly this Class object; otherwise it returns false.

Specifically, this method tests whether the type represented by the specified Class parameter can be converted to the type represented by this Class object via an identity conversion or via a widening reference conversion. See The Java Language Specification, sections 5.1.1 and 5.1.4 , for details.



来源:https://stackoverflow.com/questions/5480930/how-to-check-instanceof-on-an-argument-that-is-a-class-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!