Generating Java Dynamic Code with Generics Support

Is there any tool that provides Java code generation and also supports generics?

For example, Javassist is the tool that I need, but it does not support generics.

I wrote a small library that uses the Java 6 compiler API, however, as far as I know, it depends on the JDK. Is there a way to specify a different compiler? Or send with my application only those parts that I need to call using the Java Compiler API?

+6
java java-api java-compiler-api
source share
3 answers

It seems you can manipulate and read general information using a Javaassist. Cm

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

[jboss-user] [Javassist user questions] - Re: Changing generics Information on methods using Javassist SimonRinguette Thu, 12.20.2007 12:22:14 -0800

I read further how this was implemented by the compiler and finally found out the answer I was looking for.

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

From CtMethod, I got the Info method, add the Signature attribute. You can do this 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 you are more interested in reading a signature with generics inside, you can use methodInfo.getAttribute (SignatureAttribute.tag).

Hope this helps.

+3
source share

If you are comfortable writing bytecode, then ASM is a good library for this kind of thing. This will allow you to generate a class file on the fly without worrying about the nitty-gritty classfile format. You can then use the class loader to dynamically load it into your application.

+2
source share

If I remember correctly, it is enough to have tools.jar in the classpath to use the Java compiler at runtime.

0
source share

All Articles