2012-10-02 56 views
2

我已经构建了使用com.foo.FooEntity注释触发的注释处理器。需要能够创建更多的原型来触发该注释处理器。具有元注释的触发器注释处理器

例如,控制器也应该触发这个注释处理器。我想知道是否有办法将@FooEntity注释放在上面。喜欢的东西:

@FooEntity 
@Target(TYPE) 
@Retention(RUNTIME) 
public @interface Controller {} 

,并使用该使该类触发注释处理

@Controller 
public class MyController { ... } 

当然,这里的想法是,我想在不触碰注解处理器本身添加新的刻板印象。

回答

3

我不认为有可配置的处理器来处理@FooEntity以及注释办法元注解(在这种情况下@Controller@FooEntity。您可以改为使用支持任何注释的处理器(@SupportedAnnotationTypes("*")),然后在处理器本身中实施一些更进一步的逻辑,以决定您要处理哪些注释。这里有一个这样基于我对问题的理解的实现:

package acme.annotation.processing; 

import java.util.HashSet; 
import java.util.Set; 

import javax.annotation.processing.AbstractProcessor; 
import javax.annotation.processing.RoundEnvironment; 
import javax.annotation.processing.SupportedAnnotationTypes; 
import javax.lang.model.element.TypeElement; 

import acme.annotation.FooEntity; 

@SupportedAnnotationTypes("*") 
public class FooEntityExtendedProcessor extends AbstractProcessor { 

    private void log(String msg) { 
     System.out.println(msg); 
    } 

    @Override 
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { 
     log("Initially I was asked to process:" + annotations.toString()); 

     Set<TypeElement> fooAnnotations = new HashSet<>(); 
     for (TypeElement elem : annotations) { 
      if (isFoo(elem)) fooAnnotations.add(elem); 
     } 

     if (fooAnnotations.size() > 0) { 
      log("... but I am now going to process:" + fooAnnotations.toString()); 
      processInternal(fooAnnotations, roundEnv); 
     } else { 
      log("... but none of those was my business!"); 
     } 

     // always return false so that other processors get a chance to process the annotations not consumed here 
     return false; 
    } 

    private void processInternal(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { 
     // TODO: do your foo processing here 
    } 

    private boolean isFoo(TypeElement elem) { 
     if (elem.getQualifiedName().toString().equals("acme.annotation.FooEntity") 
       || elem.getAnnotation(FooEntity.class) != null) { 
      return true;    
     } else { 
      return false; 
     } 
    } 

} 

样品运行会给你:

Initially I was asked to process:[acme.annotation.FooEntity, skriptor.annotation.ScriptArg, java.lang.Override, skriptor.annotation.ScriptCodeRT, skriptor.annotation.ScriptCode, skriptor.annotation.ScriptObject, javax.ws.rs.Path, javax.ws.rs.GET, acme.annotation.Controller, com.sun.jersey.spi.resource.Singleton, skriptor.annotation.ScriptImport, javax.ws.rs.ext.Provider, javax.ws.rs.Produces, javax.annotation.PostConstruct] 
... but I am now going to process:[acme.annotation.Controller, acme.annotation.FooEntity]