浏览文件夹以加载课程

时间:2016-03-13 01:27:25

标签: java class packages urlclassloader

我希望能够浏览文件夹中的所有文件夹以加载这些文件夹中的类

我目前的代码没有检查所有包裹。如果没有打包,它只会加载类。

 @SuppressWarnings({"rawtypes", "unchecked"})
public Class[] getClassesFromFolder() {
    File folder = getFolder();
    String thePath = folder.getPath();
    ArrayList<Class<Script>> classes = new ArrayList<Class<Script>>();
    try {

        URL[] path = {new URL("file://" + thePath + "/Scripts/")};
        File scriptFolder = new File(getFolder().getPath() + "/Scripts");
        URLClassLoader cl = new URLClassLoader(path);
        for (String script : scriptFolder.list()) {
            if (script.contains(".class") && !script.contains("$")) {
                String truePath = script.replace(".class", "");
                try {
                    Class<?> scriptClass = (Class<?>) cl
                            .loadClass(truePath);
                    classes.add((Class<Script>) scriptClass);
                } catch (Exception e) {
                    e.printStackTrace();
                }


            }
        }
        cl.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return classes.toArray(new Class<?>[classes.size()]);
}

2 个答案:

答案 0 :(得分:0)

要加载Class对象,必须包含包前缀。因此,您需要知道类的根文件夹的存在位置。在您的情况下,它似乎是Scripts文件夹。

当您导航到子文件夹时,您需要捕获每个子文件夹名称并将其添加到您要加载的类的包前缀。

所以,例如。在Scripts下,如果你有com / packagea / packageb / classA.class 然后你需要将其加载为&#39; com.packagea.packageb.classA&#39;。再次假设Scripts是您的类的起点。

答案 1 :(得分:0)

检查此代码是否有帮助。由于声誉,我不能直接发布链接作为评论。 我从How to get all classes names in a package?获取了它 - 感谢作者。

public class ClassFinder {

    private static final char PKG_SEPARATOR = '.';

    private static final char DIR_SEPARATOR = '/';

    private static final String CLASS_FILE_SUFFIX = ".class";

    private static final String BAD_PACKAGE_ERROR = "Unable to get resources from path '%s'. Are you sure the package '%s' exists?";

    public static List<Class<?>> find(String scannedPackage) {
        String scannedPath = scannedPackage.replace(PKG_SEPARATOR, DIR_SEPARATOR);
        URL scannedUrl = Thread.currentThread().getContextClassLoader().getResource(scannedPath);
        if (scannedUrl == null) {
            throw new IllegalArgumentException(String.format(BAD_PACKAGE_ERROR, scannedPath, scannedPackage));
        }
        File scannedDir = new File(scannedUrl.getFile());
        List<Class<?>> classes = new ArrayList<Class<?>>();
        for (File file : scannedDir.listFiles()) {
            classes.addAll(find(file, scannedPackage));
        }
        return classes;
    }

    private static List<Class<?>> find(File file, String scannedPackage) {
        List<Class<?>> classes = new ArrayList<Class<?>>();
        String resource = scannedPackage + PKG_SEPARATOR + file.getName();
        if (file.isDirectory()) {
            for (File child : file.listFiles()) {
                classes.addAll(find(child, resource));
            }
        } else if (resource.endsWith(CLASS_FILE_SUFFIX)) {
            int endIndex = resource.length() - CLASS_FILE_SUFFIX.length();
            String className = resource.substring(0, endIndex);
            try {
                classes.add(Class.forName(className));
            } catch (ClassNotFoundException ignore) {
            }
        }
        return classes;
    }

    public static void main(String[] args) {
        List<Class<?>> classes = ClassFinder.find("com");
        System.out.println(classes.toString());
    }
}