2012-03-22 44 views
4

我想在AspectJ中使用@org.jboss.weld.context.ejb.Ejb注释的所有字段上声明警告。如何使用AspectJ在字段中声明警告

但我找不到如何选择该字段的方法。

我猜方面应该是类似的东西:

public aspect WrongEjbAnnotationWarningAspect { 
    declare warning : 
     within(com.queomedia..*) && 
     ??? (@org.jboss.weld.context.ejb.Ejb) 
     : "WrongEjbAnnotationErrorAspect: use javax.ejb.EJB instead of weld Ejb!"; 
} 

抑或是不可能的字段声明警告呢?

回答

2

我看到的唯一字段切入点是get和set。这是有道理的,因为方面主要是关于执行代码。声明编译器警告是一个很好的副作用。如果我们只谈论一个领域,而不考虑该领域的使用,那么切入点何时会被击中?我认为你应该可以用Annotation Processing Tool而不是AspectJ来做你想做的事情。这是第一次尝试,大部分都是从上面链接的工具网页上的示例复制的。

public class EmitWarningsForEjbAnnotations implements AnnotationProcessorFactory { 
    // Process any set of annotations 
    private static final Collection<String> supportedAnnotations 
     = unmodifiableCollection(Arrays.asList("*")); 

    // No supported options 
    private static final Collection<String> supportedOptions = emptySet(); 

    public Collection<String> supportedAnnotationTypes() { 
     return supportedAnnotations; 
    } 

    public Collection<String> supportedOptions() { 
     return supportedOptions; 
    } 

    public AnnotationProcessor getProcessorFor(
      Set<AnnotationTypeDeclaration> atds, 
      AnnotationProcessorEnvironment env) { 
     return new EjbAnnotationProcessor(env); 
    } 

    private static class EjbAnnotationProcessor implements AnnotationProcessor { 
     private final AnnotationProcessorEnvironment env; 

     EjbAnnotationProcessor(AnnotationProcessorEnvironment env) { 
      this.env = env; 
     } 

     public void process() { 
      for (TypeDeclaration typeDecl : env.getSpecifiedTypeDeclarations()) 
       typeDecl.accept(new ListClassVisitor()); 
     } 

     private static class ListClassVisitor extends SimpleDeclarationVisitor { 
      public void visitClassDeclaration(ClassDeclaration d) { 
       for (FieldDeclaration fd : d.getFields()) { 
        fd.getAnnotation(org.jboss.weld.context.ejb.Ejb.class); 
       } 

      } 
     } 
    } 
} 
1

与@JohnWatts排序的同意,但也觉得get()方法会为你工作:

declare warning : 
    within(com.queomedia..*) && 
    get(@org.jboss.weld.context.ejb.Ejb * *.*) 
    : "WrongEjbAnnotationErrorAspect: use javax.ejb.EJB instead of weld Ejb!"; 

这会在该尝试使用与@org.jboss.weld.context.ejb.Ejb注释字段的任何代码显示警告而不是字段本身,但应该足以作为编译时间警告?