2017-06-13 377 views
0

需要關於註釋處理器的幫助。我創建了一個簡單的註釋處理器,它使用@autoservice註釋來檢查註釋的字段是否是最終的。但它沒有顯示任何編譯時錯誤。這是我的配置註釋處理器@autoservice

譯註:

@Retention(RetentionPolicy.SOURCE) 
@Target(ElementType.FIELD) 
public @interface Store { 

    int temp() default 0; 
} 

註解處理器:

@SupportedAnnotationTypes("com.self.Store") 
@AutoService(Processor.class) 
public class Process extends AbstractProcessor { 

    @Override 
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { 

     for (Element element : roundEnv.getElementsAnnotatedWith(Store.class)) { 

      TypeElement typeElement = (TypeElement) element; 

      for (Element element2 : typeElement.getEnclosedElements()) { 

       VariableElement variableElement = (VariableElement) element2; 

       if (!variableElement.getModifiers().contains(Modifier.FINAL)) { 

        processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "it should be final"); 
       } 

      } 

     } 

     return true; 
    } 

} 

POM文件:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 
    <modelVersion>4.0.0</modelVersion> 
    <groupId>annotations</groupId> 
    <artifactId>annotations</artifactId> 
    <version>0.0.1-SNAPSHOT</version> 
    <name>annotation</name> 
    <dependencies> 
<dependency> 
     <groupId>com.google.auto.service</groupId> 
     <artifactId>auto-service</artifactId> 
     <version>1.0-rc2</version> 
     <optional>true</optional> 
    </dependency> 
    </dependencies> 
    <build> 
    <sourceDirectory>src</sourceDirectory> 
    <plugins> 
     <plugin> 
     <artifactId>maven-compiler-plugin</artifactId> 
     <version>3.5.1</version> 
     <configuration> 
      <source>1.8</source> 
      <target>1.8</target> 
     </configuration> 
     </plugin> 
    </plugins> 
    </build> 
</project> 

測試文件:

public class Test { 

    @Store 
    public int id; 
} 

回答

0

看起來你錯過了一個步驟。運行此項目的Maven構建將調用Google AutoService批註處理器,爲您的custom processor創建一個registration file,並使用它創建一個.jar。爲了讓您的處理器工作,即的.jar必須作爲一個依賴之前編譯包含Test項目。否則在編譯過程中生成Java ServiceLoader必須選取的註冊文件將生成,並且顯然不包含在編譯器的類路徑中。