使用 Java 注释 - 生成代码 [英] Using Java Annotations - Generating Code

查看:29
本文介绍了使用 Java 注释 - 生成代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 java 6 注释处理 api.我按照以下优秀教程创建了一个在构建时显示消息的注释处理器:

I'm using java 6 annotation processing api. I have followed the following excellent tutorial for creating an annotation processor that displays a message at build-time:

http://kerebus.com/2011/02/using-java-6-processors-in-eclipse/

但是,就我而言,我有一个简单的类:

However, in my case, I have a simple class as such:

import java.lang.annotation.ElementType;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(value = ElementType.METHOD)
public @interface Criteria {
    String id();
    double width();
    double height();
}

如您所见,上述注释在运行时使用元注释Retention"提供给 JVM.我在另一个类的源代码中使用这个标准"注释来注释一个方法,如下所示:

As you can see, the aforementioned annotation is made available to the JVM at runtime using the meta-annotation 'Retention'. I use this 'Criteria' annotation in the source code of another class to annotate a method, like so:

@Criteria(id = "fooBar", 
    width = 22, 
    height = 10
)
public void fooStream() {       
    System.out.println("foo stream method");
} 

在运行时,我想在另一个类中包含 'fooStream' 方法,仅当传入的变量与 @Criteria 注释中的元素值匹配时,即 'width' 和 'height'.我的问题是,如何在运行时采用fooStream"方法并将其注入另一个类?这甚至可能吗?我不是在寻找任何代码示例,只是对上述两个问题的回答.此外,在顶部的链接中,有一个使用JavaFileObject"和Writer"实例生成代码的示例,其中生成的代码作为字符串传递.

At runtime, I want to include the 'fooStream' method in another class, ONLY if variables that are passed in match the values of the elements in the @Criteria annotation, namely 'width' and 'height'. My question is, how could I take the method 'fooStream' and inject this into another class at run-time? Is this even possible? I'm not looking for any code examples, just answers to the two aforementioned questions. Also, in the link at the top, there is an example of generating a code using 'JavaFileObject' and 'Writer' instances, where the generated code is passed as a string.

推荐答案

如果你想在运行时修改你的,你可以使用你自己的类加载器并拦截类的加载,反省你想要的并使用 asm 库而不是原始类生成新的字节码.这不是很棘手,但您必须确定您确实需要它.

If you want runtime modification of you classes, you can use your own classloader and intercept loading of classes, introspect what you want and generate new bytecode using asm library instead of original classes. It is not very tricky, but you must be sure you need exactly that.

这篇关于使用 Java 注释 - 生成代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆