如何搜索带注释类的整个类路径?
我正在创建一个库,希望允许用户注释他们的类,因此当Web应用程序启动时,我需要扫描整个类路径以查找某些注释。
我正在考虑类似于Java EE 5 Web服务或EJB的新功能。你用@WebService或@EJB注释你的类,系统会在加载时找到这些类,这样就可以远程访问它们。
如何搜索带注释类的整个类路径?
我正在创建一个库,希望允许用户注释他们的类,因此当Web应用程序启动时,我需要扫描整个类路径以查找某些注释。
我正在考虑类似于Java EE 5 Web服务或EJB的新功能。你用@WebService或@EJB注释你的类,系统会在加载时找到这些类,这样就可以远程访问它们。
当前回答
You can find classes with any given annotation with ClassGraph, as well as searching for other criteria of interest, e.g. classes that implement a given interface. (Disclaimer, I am the author of ClassGraph.) ClassGraph can build an abstract representation of the entire class graph (all classes, annotations, methods, method parameters, and fields) in memory, for all classes on the classpath, or for classes in whitelisted packages, and you can query that class graph however you want. ClassGraph supports more classpath specification mechanisms and classloaders than any other scanner, and also works seamlessly with the new JPMS module system, so if you base your code on ClassGraph, your code will be maximally portable. See the API here.
其他回答
您可以使用Java Pluggable Annotation Processing API编写注释处理器,该处理器将在编译过程中执行,并将收集所有注释类并构建索引文件以供运行时使用。
这是可能进行带注释类发现的最快方式,因为您不需要在运行时扫描类路径,这通常是非常缓慢的操作。此外,这种方法适用于任何类加载器,而不仅仅适用于运行时扫描程序通常支持的urlclassloader。
上述机制已经在ClassIndex库中实现。
使用@IndexAnnotated元注释注释您的自定义注释。这将在编译时创建一个索引文件:META-INF/annotations/com/test/YourCustomAnnotation,列出所有带注释的类。你可以在运行时通过执行以下命令访问索引:
ClassIndex.getAnnotated(com.test.YourCustomAnnotation.class)
Classloader API没有“枚举”方法,因为类加载是一个“按需”活动——在类路径中通常有数千个类,其中只有一小部分是需要的(目前仅rt.jar就有48MB !)
因此,即使您可以枚举所有的类,这也会非常耗费时间和内存。
简单的方法是在设置文件(xml或任何适合你的文件)中列出相关的类;如果您希望自动执行此操作,请将自己限制在一个JAR或一个类目录中。
Spring有一个AnnotatedTypeScanner类。 这个类内部使用
ClassPathScanningCandidateComponentProvider
该类具有实际扫描类路径资源的代码。它通过使用运行时可用的类元数据来实现这一点。
可以简单地扩展这个类或使用相同的类进行扫描。下面是构造函数定义。
/**
* Creates a new {@link AnnotatedTypeScanner} for the given annotation types.
*
* @param considerInterfaces whether to consider interfaces as well.
* @param annotationTypes the annotations to scan for.
*/
public AnnotatedTypeScanner(boolean considerInterfaces, Class<? extends Annotation>... annotationTypes) {
this.annotationTypess = Arrays.asList(annotationTypes);
this.considerInterfaces = considerInterfaces;
}
现在回答还来得及吗? 我想说,最好使用类库,如ClassPathScanningCandidateComponentProvider或Scannotations
但即使有人想用classLoader来尝试一下,我也自己写了一些来打印包中类的注释:
public class ElementScanner {
public void scanElements(){
try {
//Get the package name from configuration file
String packageName = readConfig();
//Load the classLoader which loads this class.
ClassLoader classLoader = getClass().getClassLoader();
//Change the package structure to directory structure
String packagePath = packageName.replace('.', '/');
URL urls = classLoader.getResource(packagePath);
//Get all the class files in the specified URL Path.
File folder = new File(urls.getPath());
File[] classes = folder.listFiles();
int size = classes.length;
List<Class<?>> classList = new ArrayList<Class<?>>();
for(int i=0;i<size;i++){
int index = classes[i].getName().indexOf(".");
String className = classes[i].getName().substring(0, index);
String classNamePath = packageName+"."+className;
Class<?> repoClass;
repoClass = Class.forName(classNamePath);
Annotation[] annotations = repoClass.getAnnotations();
for(int j =0;j<annotations.length;j++){
System.out.println("Annotation in class "+repoClass.getName()+ " is "+annotations[j].annotationType().getName());
}
classList.add(repoClass);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* Unmarshall the configuration file
* @return
*/
public String readConfig(){
try{
URL url = getClass().getClassLoader().getResource("WEB-INF/config.xml");
JAXBContext jContext = JAXBContext.newInstance(RepositoryConfig.class);
Unmarshaller um = jContext.createUnmarshaller();
RepositoryConfig rc = (RepositoryConfig) um.unmarshal(new File(url.getFile()));
return rc.getRepository().getPackageName();
}catch(Exception e){
e.printStackTrace();
}
return null;
}
}
在配置文件中,放入包名并将其解编到一个类。
谷歌反射,如果你也想发现接口。
Spring ClassPathScanningCandidateComponentProvider没有发现接口。