简体   繁体   English

如何从Java目录加载特定类的实例?

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

Here's my method: 这是我的方法:

Feature[] getFeatures(File dir) 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;

    }

Using: 使用方法:

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

Note, however, that this relies on the ClassLoader. 但是请注意,这依赖于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. 认为应该可以,但是如果不能,那么至少可以使您走上正确的道路。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM