【问题标题】:Load new objects if the class files exists in the folder如果文件夹中存在类文件,则加载新对象
【发布时间】:2015-02-24 11:41:23
【问题描述】:

有没有办法检查文件夹中的所有类文件,如果文件夹中存在每个文件,则为每个文件创建一个新对象?对于java...

【问题讨论】:

标签: java


【解决方案1】:

这是从目录调用类的示例。

public class InvokeClass {
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {

        try {
            String classDerectory = "C:\\classes";
            File folder = new File(classDerectory);
            // read derectory 
            for (final File fileEntry : folder.listFiles()) {
                // URLClassLoader so convert file to url
                URLClassLoader classLoader = new URLClassLoader(new URL[]{fileEntry.toURI().toURL()});
                //get class from loader
                Class<?> clazz = classLoader.loadClass(fileEntry.getName());
                // get new instance
                Object obj=clazz.newInstance();
                // do something with object.......
            }


        } catch (Exception e) {
            // something went wrong..
            e.printStackTrace();
        }

    }
}

【讨论】:

    猜你喜欢
    • 2011-02-19
    • 2013-12-24
    • 1970-01-01
    • 1970-01-01
    • 2018-02-10
    • 1970-01-01
    • 2013-01-17
    • 2011-01-19
    相关资源
    最近更新 更多