java-compiler-api - 支持泛型的 Java 动态代码生成

标签 java-compiler-api java dynamic-code

有没有提供Java动态代码生成并且还支持泛型的工具?

例如Javassist,就是我需要的那种工具,但是它不支持泛型。

我写了一个使用 Java 6 编译器 API 的小库,但据我所知它依赖于 JDK。有没有办法指定另一个编译器?或者仅随我的应用程序提供我需要使用 Java Compiler API 调用的部分?

最佳答案

您似乎可以使用 Javaassist 操作和读取通用信息。见

http://www.mail-archive.com/jboss-user@lists.jboss.org/msg101222.html

[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.

You can defenitely do that with javaassist. The key class is javassist.bytecode.SignatureAttribute.

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

If your more interesed in reading the signature with the generics inside, you can use the methodInfo.getAttribute(SignatureAttribute.tag).

I hope this helped.

关于java-compiler-api - 支持泛型的 Java 动态代码生成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3596723/

相关文章:

具有自定义 ClassLoader 和 FileManager 的 JavaCompiler

java - Annotation Bind Time(Java中什么时候绑定(bind)注解)

java - 字符串太大,无法使用 UTF-8 进行编码,而改为 'STRING_TOO_LARGE'

嵌入式系统上的 C++ 动态代码注入(inject)

c# - 通过 Web 服务公开 system.dll 是否存在安全问题?

java - Java 13 和 Java 8 中的交叉编译

java - 是否可以在 sonarqube 的多模式项目中跳过 Java 插件

java - 为什么死锁没有发生?

java - 在 Debug模式下运行程序非常慢

c# - 如何在动态生成的C#代码中初始化各种类型变量?