获取指定包下的所有类


/**
 * 获取指定包下的所有类
 * @author kevin
 *
 */
public class PackageUtil {
	  public static List 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 getClassNamefFromPachage(String packageName) throws IOException, ClassNotFoundException {
		Enumeration iterator = Thread.currentThread().getContextClassLoader().getResources(packageName.replace(".", "/"));
		Listlist = new ArrayList();
		
		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;
		
	}
}


你可能感兴趣的:(java)