繁体   English   中英

Java 6 - 注释处理器和代码添加

[英]Java 6 - Annotation processor and code addition

我写了一个自定义注释,其中包含属性和AnnotationProcessor元数据:

@SupportedAnnotationTypes({"<package>.Property"})
public class PropertyProcessor extends AbstractProcessor {

    @Override
    public boolean process(Set<? extends TypeElement> annotations,
            RoundEnvironment roundEnv) {
        // Get messager object
        Messager messager = processingEnv.getMessager();
        // Iterate through the annotations
        for(TypeElement typeElement : annotations) {
            // Iterate through the annotated elements
            for(Element element : roundEnv.getElementsAnnotatedWith(typeElement)) {
                // Get Property annotation
                Property property = element.getAnnotation(Property.class);

            }
        }
        return false;
    }

}

这是一个问题,我之前使用过Javassist,但它依赖于类加载器,我认为它不适合OSGi应用程序。 我想在编译具有Property注释的类时更改生成的字节码。

你试过Google Guice吗?

Google Guice允许您通过拦截方法进行面向方面编程。 如果这就是你需要做的全部,你可以实现一个MethodInterceptor,它允许你在运行时覆盖方法。 它非常适合隔离交叉问题。

例如,假设您想要阻止某些方法在周末执行,您可以这样注释它们:

@Property
public class SomeClass {
    public Receipt doSometing() {
        // Do something
    }
}

定义一个MethodInterceptor:

public class PropertyInterceptor implements MethodInterceptor {
  public Object invoke(MethodInvocation invocation) throws Throwable {
    // For example prevent the classes annotated with @Property
    // from being called on weekends
    Calendar today = new GregorianCalendar();
    if (today.getDisplayName(DAY_OF_WEEK, LONG, ENGLISH).startsWith("S")) {
      throw new IllegalStateException(
          invocation.getMethod().getName() + " not allowed on weekends!");
    }
    return invocation.proceed();
  }
}

然后将拦截器绑定到注释:

public class PropertyModule extends AbstractModule {
  protected void configure() {
        PropertyInterceptor propertyInterceptor = new PropertyInterceptor();        
        bindInterceptor(Matchers.annotatedWith(Property.class), 
        Matchers.any(), propertyInterceptor);
  }
}

简短的回答是:您不应该在注释处理期间更改源代码。

我最近遇到的情况是答案不理想(见这个问题 )。 我的解决方案是使用内部javac api以编程方式添加我需要的代码。 有关详细信息,请参阅我对自己问题的回答

我从Project Lombok那里得到了灵感,从他们的源代码开始,扔掉了我不需要的一切。 我不认为你会找到一个更好的起点。

顺便说一下,Javassist可能无济于事,因为你正在处理源代码树,而不是字节代码。 如果要使用字节代码操作库,可以在编译后静态地执行,也可以在加载类时动态执行,但不能在注释处理期间执行,因为这是预编译步骤。

注释处理并不意味着改变现有的类 - 它只是用于生成额外的代码/资源(在逐个类的基础上,否则在仅重新编译修改的源时会遇到麻烦)。

前段时间我曾尝试使用Spoon来解决类似的问题:我非常喜欢程序处理器的想法(以及更多的IDE集成),但当时它并不是很稳定......

根据您的使用情况,AOP工具(例如: AspectJ )可以比Spoon更好地为您提供服务,当然 - 您可以随时使用源代码生成器或实现完整的DSL(看看精彩的Xtext ) 。

根据你的队友的规模,周转率和“智力惯性” - 你可以更好地承受普通java的痛苦而不是引入新工具/技术,形成同事并将新工具集成到你的CI系统。 仔细权衡成本/收益。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM