当我将Class
作为方法参数传递时,编译器是否可能检查Class
上是否定义了Annotation
?
我想使用Interface
作为标记MarkerInterface
。而不是使用接口void method(Class<? extends MarkerInerface>);
:
Annotation
我希望编译器检查MyAnnotation
。例如void method(Class<? annotates MyAnnotation>);
:
method(Object.class); // Error since Object doesn't have MyAnnotation defined
method(MyClass.class); // fine.
@MyAnnotation
public class MyClass {...}
有办法吗?
编辑:以下代码应导致编译器错误:
{{ context }}
答案 0 :(得分:2)
Checker Framework做你想要的。你写的语法是Class<? extends @MyAnnotation Object>
而不是Class<? annotates MyAnnotation>
。
这是一个测试用例:
import org.checkerframework.checker.interning.qual.Interned;
public class ClassWithAnnotationTest {
@Interned
public class MyClass {}
void method(Class<? extends @Interned Object> arg) {}
void client() {
method(Object.class); // Error, Object isn't annotated by @Interned.
method(MyClass.class); // Fine.
}
}
这是编译器输出:
$ch/bin/javac -g ClassWithAnnotationTest.java -processor interning
ClassWithAnnotationTest.java:11: error: [argument.type.incompatible] incompatible types in argument.
method(Object.class); // Error, Object isn't annotated by @Interned.
^
found : @Interned Class<Object>
required: @Interned Class<? extends @Interned Object>
1 error
答案 1 :(得分:0)
你可以使用这样的东西,但首先要准备你的注释列表 添加到扫描仪。
ClassPathScanningCandidateComponentProvider scanner =
new ClassPathScanningCandidateComponentProvider(<DO_YOU_WANT_TO_USE_DEFALT_FILTER>);
scanner.addIncludeFilter(new AnnotationTypeFilter(<TYPE_YOUR_ANNOTATION_HERE>.class));
for (BeanDefinition bd : scanner.findCandidateComponents(<TYPE_YOUR_BASE_PACKAGE_HERE>))
System.out.println(bd.getBeanClassName());