2017-04-09 83 views
1

當我通過Class作爲方法參數時,編譯器是否有可能檢查Annotation是否在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 {...} 
+0

你可以讓你的問題更具體,如通過顯示符合客戶端的代碼,編譯器應該批准,並顯示編譯器應該爲其發出警告的不合格客戶端代碼? – mernst

+0

完成。希望現在清楚。順便說一句。我更多地考慮編譯器錯誤而不是警告。 – Armin

回答

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()); 
+0

這很好,但不符合我的需求。 – Armin

1

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