得到包下所有类

来源:互联网 发布:mysql自动增长赋值 编辑:程序博客网 时间:2024/06/10 09:49
 private static List<Class> getClass(String packageName) {

        File file = new File("");

// 为了打包后运行jar包可以得到地址

        String filePath = "/" + file.getAbsolutePath().replace("\\", "/")
                + "/WebContent/WEB-INF/classes/" + packageName;
        List<Class> fileNames = getClass(filePath, null);
        return fileNames;
    }

    private static List<Class> getClass(String filePath, List<Class> className) {
        List<Class> myClass = new ArrayList<Class>();
        File file = new File(filePath);
        File[] childFiles = file.listFiles();
        for (File childFile : childFiles) {
            if (childFile.isDirectory()) {
                myClass.addAll(getClass(childFile.getPath(), myClass));
            } else {
                String childFilePath = childFile.getPath();
                childFilePath = childFilePath.substring(childFilePath
                        .indexOf("\\classes") + 9, childFilePath
                        .lastIndexOf("."));
                childFilePath = childFilePath.replace("\\", ".");
                try {
                    myClass.add(Class.forName(childFilePath));
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
        return myClass;
    } 
0 0