使用Java注解 - 生成code [英] Using Java Annotations - Generating Code

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

问题描述

我使用的是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 /使用Java的-6处理器,在日食/

不过,在我的情况,我有一个简单的类这样:

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();
}

正如你所看到,上述标注是使用元注释保留提供给JVM运行时。我使用另一个类的源$ C ​​$ C这个标准进行注解的方法,像这样:

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注释元素的值,即宽度和高度。我的问题是,我怎么能走法fooStream,并注入在运行时另一类?这甚至可能?我不会找任何code的例子,只是要回答上述两个问题。此外,在顶部的链接,有一个使用'JavaFileObject中'和'作家'的情况下,如果生成的code作为一个字符串传递产生code的例子。

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库,而不是原来的类生成新的字节code。这不是很靠谱,但是你一定要确定你需要这一点。

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注解 - 生成code的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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