取得接口的所有实现
取得一个接口的所有实现class
package com.hp.util;import java.io.File;import java.net.URL;import java.util.ArrayList;import java.util.Collection;import java.util.Enumeration;import java.util.List;@SuppressWarnings("all")public class ClassUtil {public static List<Class> getAllClassByInterface(Class c) {List<Class> list = new ArrayList<Class>();if (c.isInterface()) {String packageName = c.getPackage().getName();try {List<Class> allClass = getClasses(packageName);for (int i = 0; i < allClass.size(); i++) {if (c.isAssignableFrom(allClass.get(i))) {if (!c.equals(allClass.get(i))) {list.add(allClass.get(i));}}}} catch (Exception e) {e.printStackTrace();}}return list;}private static List<Class> getClasses(String packageName) throws Exception{ClassLoader cl = Thread.currentThread().getContextClassLoader();String path = packageName.replace(".", "/");Enumeration<URL> resources = cl.getResources(path);List<File> dirs = new ArrayList<File>();while (resources.hasMoreElements()) {URL resource = resources.nextElement();dirs.add(new File(resource.getFile()));}List<Class> list = new ArrayList<Class>();for (File directory : dirs) {list.addAll(findClasses(directory, packageName));}return list;}private static List<Class> findClasses(File directory, String packageName) throws ClassNotFoundException{List<Class> list = new ArrayList<Class>();if (!directory.exists()) {return list;}File[] files = directory.listFiles();for (File file : files) {if (file.isDirectory()) {assert !file.getName().contains(".");list.addAll(findClasses(file, packageName+"."+file.getName()));} else if (file.getName().endsWith(".class")) {list.add(Class.forName(packageName+"."+file.getName().substring(0, file.getName().length() - 6)));}}return list;}}