Search code examples
javaclassclassloaderinstanceof

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


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?


Solution

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