gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:15:24 24 4
gpt4 key购买 nike

有没有提供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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com