java 根據接口,返回因此的接口實現類

package com.dic.factory;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

public class ClassUtils {
	
	/**
	 * 返回接口因此的實現類.
	 * @param c
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static List<Class> getAllClassByInterface(Class c) {
		List<Class>  returnClassList = null;
		
		if(c.isInterface()) {
			// 獲取當前的包名
			String packageName = c.getPackage().getName();
			try {
				// 獲取當前包下以及子包下因此的類
				List<Class> allClass = getClasses(packageName);
				if(allClass != null) {
					returnClassList = new ArrayList<Class>();
					for(Class classes : allClass) {
						// 判斷是不是同一個接口
						if(c.isAssignableFrom(classes)) {
							// 自己不加入進去
							if(!c.equals(classes)) {
								returnClassList.add(classes);		
							}
						}
					}
				}
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		return returnClassList;
	}
	
	@SuppressWarnings("rawtypes")
	private static List<Class> getClasses(String packageName) throws ClassNotFoundException, IOException {
		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();	
		String path = packageName.replace(".", "/");
		Enumeration<URL> resources = classLoader.getResources(path);
		List<File> dirs = null;
		if(resources != null) {
			dirs = new ArrayList<File>();
			while(resources.hasMoreElements()) {
				URL resource = resources.nextElement();
				dirs.add(new File(resource.getFile()));
			}
		}
		List<Class> classes = null;
		if(dirs != null) {
			classes = new ArrayList<Class>();
			for(File directory : dirs) {
				classes.addAll(findClasses(directory,packageName));
			}
		}
		
		return classes;
	}
	
	@SuppressWarnings("rawtypes")
	private static List<Class> findClasses(File directory,String packageName) throws ClassNotFoundException {
		List<Class> classes = null;
		if(!directory.exists()) {
			return classes;
		}
		File[] files = directory.listFiles();
		if(files != null) {
			classes = new ArrayList<Class>();
			for(File file :  files) {
				if(file.isDirectory()) {
					classes.addAll(findClasses(file,packageName+"."+file.getName()));
				}else if(file.getName().endsWith(".class")) {
					classes.add(Class.forName(packageName+"."+file.getName().substring(0, file.getName().length()-6)));
				}
			}
		}
		
		return classes;
	}
}
相關文章
相關標籤/搜索