package com.wp.tool; import java.io.File; import java.util.ArrayList; import java.util.List; /** * 获取非jar包的的classes *例子* Created by wp on 2017/7/21 0021. */ public class ClassKit { private static File classPathRootDirectory = null; private static List
allClassesName = null; private static List > allClass = null; static { ClassKit.classPathRootDirectory = new File(File.class.getClass().getResource("/").getPath()); ClassKit.allClassesName = ClassKit.parseDir2ClassName(ClassKit.classPathRootDirectory,true); ClassKit.allClass = ClassKit.name2Classes(ClassKit.allClassesName); } /** * 将类的全限定名list 转换为 class list * * @param names * @return */ private static List > name2Classes(List names) { List > classes = null; for (String className : names) { Class clz = null; try { clz = Class.forName(className); } catch (ClassNotFoundException e) { continue; } if (classes == null) { classes = new ArrayList >(); classes.add(clz); } else { classes.add(clz); } } return classes; } /** * 获取某一个包下面的class * * @param pkg 包名 * @param recursion 是否递归 * @return */ public static List > packageClassName(String pkg,boolean recursion) { String[] split = pkg.split("\\."); String path = ""; for (String s : split) { path += s + File.separator; } File file = new File(ClassKit.classPathRootDirectory,path); List list = parseDir2ClassName(file,recursion); List > classes = ClassKit.name2Classes(list); return classes; } /** * 获取某个文件夹下面所有的类 * * @param dir * @param recursion 是否递归 * @return List */ private static List parseDir2ClassName(File dir,boolean recursion) { if (dir.isFile()) throw new RuntimeException("Is Not a Directory"); List list = new ArrayList (); File[] fileList = dir.listFiles(); for (File tmp : fileList) { if (tmp.isFile()) { String path = tmp.getAbsolutePath(); int len = ClassKit.classPathRootDirectory.getAbsolutePath().length(); String replace = path.substring(len + 1).replace(File.separator, "."); if (replace.endsWith(".class")) { int i = replace.lastIndexOf(".class"); list.add(replace.substring(0, i)); } } else if(recursion){ List strings = parseDir2ClassName(tmp,recursion); list.addAll(strings); } } return list; } public static List getAllClassesName() { return ClassKit.allClassesName; } public static List > getAllClass() { return ClassKit.allClass; } }
public static void main(String[] args) { List> allClass = ClassKit.getAllClass(); for(Class clz : allClass){ System.out.println(clz.getSimpleName()); } System.out.println("***********"); List allClassesName = ClassKit.getAllClassesName(); for(String className : allClassesName){ System.out.println(className); } System.out.println("***********"); List > pkgClasses = ClassKit.packageClassName("com.myoldtime.ioc", true); for(Class p : pkgClasses){ System.out.println(p.getSimpleName()); } }