[Spoon-discuss] code creation using factories

Renaud Pawlak renaud.pawlak at gmail.com
Sun Nov 9 18:19:32 CET 2008


Hi,

You are missing the target and the arguments of the invocation. You
should avoid the core factory methods because they are too simple...

Factory f=...;

f.Code().createInvocation(f.Field().createReference("java.lang.System.out"),
f.Executable().createReference("void
java.io.PrintStream.println(java.lang.String)"),
f.Code().createLiteral("hello world"));

Note1: I am not so sure about the format of the strings.. to be
checked in the code if anything goes wrong.

Note2: you can also use code snippets to create simple code... it is
of course not very nice (no AST there) but simpler to write...

f.Code().createCodeSnippetExpression(java.lang.System.out.println("hello
world"));

Note3: the cleanest and checked way it through templates, of course.

Cheers,
/Renaud

On Sun, Nov 9, 2008 at 3:39 PM, Jakub Mikulski <kuba.mikulski at gmail.com> wrote:
> Hello,
>
> I'm using Spoon to create some new code based on annotations in processed
> classes (no templates, I'm trying to do this using factories). I have
> successfully created a new class and its methods. Now I'm trying to add some
> code to these methods, but I'm having some problems... Let's say I want to
> add a classic System.out.println("Hello world!") to a method which code
> block is referenced by cb. My code looks like this:
>
> // crf, ef, tf are factories (Core, Executable, Type)
> CtInvocation<?> inv = crf.createInvocation();
> List<CtTypeReference<?>> args = new LinkedList<CtTypeReference<?>>();
> args.add(tf.createReference("java.lang.String"));
> CtExecutableReference ref =
> ef.createReference(tf.createReference("java.io.PrintStream"),
> tf.createReference("void"), "println", args);
> inv.setExecutable(ref);
> cb.insertBegin(inv);
>
> I have no idea how to specify that the PrintStream I'm calling this method
> on is System.out, and that the String argument is "Hello world!" -
> accordingly, the resulting code block in the new method is simply {
> println(); }. Any leads...?
>
> Thanks in advance,
> km
>
> _______________________________________________
> Spoon-discuss mailing list
> Spoon-discuss at lists.gforge.inria.fr
> http://lists.gforge.inria.fr/cgi-bin/mailman/listinfo/spoon-discuss
>



-- 
Renaud Pawlak, Professor
ISEP - 21 rue d'Assas 75006 Paris, France
Head of the Computer Engineering Department
Head of ISEP Research and Consulting for Computer Engineering
Phone: +33 149 54 52 78
Cell #1: +33 6 37 29 12 15
Cell #2: +33 6 36 47 06 01
Fax: +33 1 49 54 52 51
http://renaudpawlak.wikidot.com




More information about the Spoon-discuss mailing list