Bijan
Bijan

Reputation: 6772

How do I load instances of a certain class from a java directory?

Here's my method:

Feature[] getFeatures(File dir)

I'm trying to go through the directory, check each class file. Any class that is of type 'Feature', I want to load an instance of it. Then I want to return an array of these instances.

How is this done?

Thank you.

EDIT:

Here's what I have now:

private static LinkedList<Feature> getFeaturesInDirectory(File dir) throws ClassNotFoundException {

        LinkedList<Feature> features = new LinkedList<Feature>();

        ClassLoader cl = new IndFeaClassLoader();

        // list all files in directory
        for(String s : dir.list()) {
            Class klass = cl.loadClass(s);
            try {
                Object x = klass.newInstance();
                if (x instanceof Feature) {
                    features.add((Feature)x);
                }
            } catch (InstantiationException ex) {
            } catch (IllegalAccessException ex) {
            }

        }

        return features;

    }

Upvotes: 0

Views: 321

Answers (1)

Brian Roach
Brian Roach

Reputation: 76908

Using:

MyClassName mcn = (MyClassName) Class.forName("MyClassName").newInstance();

Note, however, that this relies on the ClassLoader. If the classes are not coming from the same location as your current class (or the system classloader) you need to specify a classloader:

File myDir = new File("/some/directory/");
ClassLoader loader = null;
try {
    URL url = myDir.toURL();         
    URL[] urls = new URL[]{url};
    ClassLoader loader = new URLClassLoader(urls);
} 
catch (MalformedURLException e) 
{
    // oops
}

MyClassName mcn = 
    (MyClassName) Class.forName("MyClassName", true, loader).newInstance();

I think that should work, but if not it should at least put you on the right path.

Upvotes: 1

Related Questions