Java动态代码生成,支持泛型 [英] Java Dynamic Code Generation with support for generics
问题描述
是否有任何工具可以提供Java动态代码生成并且还支持泛型?
Is there any tool which provides Java dynamic code generation and that also supports generics?
例如,Javassist是我需要的那种工具,但它确实如此不支持泛型。
Javassist for example, is the kind of tool that I need, but it does not support generics.
我写了一个使用Java 6 Compiler API的小型lib,但据我所知它依赖于JDK。有没有办法指定另一个编译器?或者我的应用程序只附带我需要使用Java Compiler API调用的部分?
I wrote a small lib which uses the Java 6 Compiler API, however as far as I know it depends on JDK. Is there a way to specify another compiler? Or to ship with my application only the parts that I need to invoke with the Java Compiler API?
推荐答案
看来你可以操纵并使用Javaassist读取通用信息。见
It seems you can manipulate and read generic info with Javaassist. See
http://www.mail-archive.com/jboss-user@lists.jboss.org/msg101222.html
[jboss-user] [Javassist用户问题] - Re:使用Javassist改变方法的泛型信息
SimonRinguette
Thu,2007年12月20日12:22:14 -0800
[jboss-user] [Javassist user questions] - Re: Altering Generics Information of Methods using Javassist SimonRinguette Thu, 20 Dec 2007 12:22:14 -0800
我已经进一步阅读了编译器如何实现这一点,
终于找到了我想要的答案。
I have done further reading on how this is implemented by the compiler and finally found out the answer I was looking for.
您可以使用javaassist进行defenitely。关键类是
javassist.bytecode.SignatureAttribute。
You can defenitely do that with javaassist. The key class is javassist.bytecode.SignatureAttribute.
从CtMethod,我已经获得了methodInfo,我添加了一个Signature属性。你可以这样做:
From a CtMethod, i've obtained the methodInfo I add a Signature attribute. You can do it with something like:
CtMethod method = ....
MethodInfo methodInfo = method.getMethodInfo();
SignatureAttribute signatureAttribute = new
SignatureAttribute(methodInfo.getConstPool(),
"()Ljava/util/List<Ljava/lang/String;>;");
methodInfo.addAttribute(signatureAttribute);
如果您更喜欢阅读里面的仿制品签名,那么你
可以使用methodInfo.getAttribute(SignatureAttribute.tag)。
If your more interesed in reading the signature with the generics inside, you can use the methodInfo.getAttribute(SignatureAttribute.tag).
我希望这有帮助。
这篇关于Java动态代码生成,支持泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!