java - IClassFile 注释

标签 java eclipse eclipse-jdt

在 Eclipse 中使用 IClassFile 时如何检查注释?

这似乎不起作用 classFile.getClass().isAnnotationPresent?如有任何帮助,我们将不胜感激。

使用问题

for (final IClassFile classFile : classFiles) {
    IAnnotation[] annotations = classFile.getType().getAnnotations();

我必须获取所有包,然后获取该包中的类文件,然后获取注释。需要 3 个循环。有没有办法尽量减少这种情况?

最佳答案

我想说,查找注释的最简单方法是通过三重循环,但使用“SearchEngine instead. Take a look at the source code for the”可能会稍微快一些(假设您正在查找特定注释)。 org.eclipse.jdt.internal.junit.launcher.JUnit4TestFinder` 类。它查找用 @Test 或 @RunWith 注释的(源)类,这与您想要做的类似,但针对的是二进制类。

你会做这样的事情:

IJavaElement[] allPackagesToSearch = ...
SearchRequestor requestor = <implement the SearchRequestor abstract class and store all matches>

IJavaSearchScope scope= SearchEngine.createJavaSearchScope(binaryPackages, IJavaSearchScope.APPLICATION_LIBRARIES);
int matchRule= SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE;
SearchPattern runWithPattern= SearchPattern.createPattern("com.foo.MyAnnotation", IJavaSearchConstants.ANNOTATION_TYPE, IJavaSearchConstants.ANNOTATION_TYPE_REFERENCE, matchRule);
SearchParticipant[] searchParticipants= new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() };
new SearchEngine().search(annotationsPattern, searchParticipants, scope, requestor, new SubProgressMonitor(pm, 2));

这有点拗口,为了弄清楚它是如何工作的,我建议阅读 SearchEngine、SearchPattern 和 SearchRequestor 的 JavaDoc。

如果您想查找所有个注释,请更改匹配规则,使用“*”代替“com.foo.MyAnnotation”。

关于java - IClassFile 注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12505194/

相关文章:

java - 适用于 Android 的 Zxing 条码匹配应用程序

java - 通过 API 在 Google Drive 上共享文件时防止默认 "Editors will be allowed to add people and change the permissions"行为

java - 如何在 Hadoop 中使用 CompressionCodec

eclipse - 没有 Eclipse 的 JDT?

eclipse - 在 Eclipse 中以编程方式折叠

java - 如何使用JDT确定类是AnnotationDeclaration还是TypeDeclaration

java - 为什么在执行多对多查询时我的 Set 变量会抛出错误?

java - 在eclipse中编译java程序

java - 从外部访问 JFrame 内容

java - Eclipse和Mysql连接错误