News
- 12-04-2012: Spoon 1.5 is released.
Spoon in 1 minute
Spoon enables you to transform (see below) and analyze Java source code (see example) . Spoon provides a complete and fine-grained Java metamodel where any program element (classes, methods, fields, statements, expressions...) can be accessed both for reading and modification. Spoon takes as input source code and produces transformed source code ready to be compiled.
Spoon is Free and Open Source (CeCILL-C license - French equivalent to LGPL).
Getting started / Tutorial
To automatically insert a bound check in the following code:
public void openUserSpacePort(@Bound(min = 1025) int a) {
// code to open a port
}
The following Spoon code has to be written:
public @interface Bound {
double min();
}
// we only process method parameters (CtParameter) annotated with @Bound
public class Bound2Processor extends
AbstractAnnotationProcessor<Bound, CtParameter<?>> {
public void process(Bound annotation, CtParameter<?> element) {
// we declare a new snippet of code to be inserted
CtCodeSnippetStatement snippet = getFactory().Core().createCodeSnippetStatement();
// this snippet contains an if check
snippet.setValue("if(" + element.getSimpleName() + " < "
+ annotation.min()
+ ") throw new RuntimeException(\"[Spoon check] Bound violation\");");
// we insert the snippet at the beginning of the method boby
element.getParent(CtMethod.class).getBody().insertBegin(snippet);
}
}
and launched as follows:
$ java -cp spoon.jar spoon.Launcher -i sourceFolder -p Bound2Processor
Spoon processes all source files of sourceFolder and writes to the resulting code to the folder "spooned". For our example:
public void openUserSpacePort(int a) {
if(a < 1025) throw new RuntimeException("[Spoon check] Bound violation");
// code to open a port
}
Downloads
| Spoon (standalone) | Latest Release - 1.5 | download | javadoc |

