獲取指定包下的所有類
阿新 • • 發佈:2018-12-16
/** * 獲取指定包下的所有類 * @author kevin * */ public class PackageUtil { public static List<String> getClassName(String packageName) throws IOException { try { return getClassNamefFromPachage(packageName); } catch (ClassNotFoundException e) { e.printStackTrace(); } return null; } /** * 獲取指定包下面的所有類 * @param packageName 包名 * @return 類的完整名稱 (不包括字尾) * @throws IOException * @throws ClassNotFoundException */ private static List<String> getClassNamefFromPachage(String packageName) throws IOException, ClassNotFoundException { Enumeration<URL> iterator = Thread.currentThread().getContextClassLoader().getResources(packageName.replace(".", "/")); List<String>list = new ArrayList<String>(); URL url = null; File file = null; File[] fls = null; Class<?> c = null; String className = null; String classFullName = null; while(iterator.hasMoreElements()) { url = iterator.nextElement(); if ("file".equals(url.getProtocol())) { file = new File(url.getPath()); System.out.println(file); if (file.isDirectory()){ fls= file.listFiles(); for(File fl :fls) { className = fl.getName(); className = className.substring(0,className.lastIndexOf(".")); //獲取該類的類名 person classFullName = packageName+"."+className;//該類的完整名稱,例如com.xx.person c=Thread.currentThread().getContextClassLoader().loadClass(classFullName); list.add(classFullName); } } } } return list; } }