[java]代码库
package class_scanner;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
/**
* <p>
* 扫描特定目录下面的class文件,参考spring的component scan实现
* 可以支持普通文件(tomcat),jar包和<b>VFS(jboss)</b>
* </p>
* @Required spring-core-3.2.3
* @author luis.chen
* @version $Id: ClassScanner.java, v 0.1 2014年6月30日 下午2:53:29 luis.chen Exp $
*/
public class ClassScanner {
/**
* 通过包名定位下面所有的class文件
* @param packageName 包名格式com.xxx.yyy
* @throws IOException
* @throws ClassNotFoundException
* */
public static Set<Class<?>> loadClassByPackage(String packageName) throws IOException, ClassNotFoundException{
Set<Class<?>> clzSet = new HashSet<Class<?>>();
//定义资源格式为class后缀
String resourcePattern = "**/*.class";
//用于搜索的完整路径
//格式为 classpath*:aaa/bbb/cc/**/*.class
String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
packageName.replaceAll("\\.", "/") + "/" + resourcePattern;
ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
Resource[] resources = resourcePatternResolver.getResources(packageSearchPath);
for (Resource resource : resources) {
//去掉.class 获得真正的类名
String className = resource.getFilename().substring(0, resource.getFilename().length() - 6);
clzSet.add(Class.forName(packageName+"."+className));
}
return clzSet;
}
public static void main(String args[]){
String pkgName = "bean_mapping";
try {
Set<Class<?>> clzSet = ClassScanner.loadClassByPackage(pkgName);
for(Class<?> clz: clzSet){
System.out.println(clz.getName());
//输出如下
/*
bean_mapping.Name2
bean_mapping.TestBeanMapping
bean_mapping.Name
bean_mapping.SrcObjectMapper
bean_mapping.DescObj
bean_mapping.SourceObj
*/
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}