use of spoon.reflect.factory.CodeFactory in project spoon by INRIA.
the class CompilationTest method compileTest.
@Test
public void compileTest() throws Exception {
// contract: the modified version of classes is the one that is compiled to binary code
final Launcher launcher = new Launcher();
launcher.addInputResource("./src/test/resources/noclasspath/Simple.java");
File outputBinDirectory = new File("./target/class-simple");
if (!outputBinDirectory.exists()) {
outputBinDirectory.mkdirs();
}
launcher.setBinaryOutputDirectory(outputBinDirectory);
launcher.getEnvironment().setShouldCompile(true);
launcher.buildModel();
Factory factory = launcher.getFactory();
CoreFactory core = factory.Core();
CodeFactory code = factory.Code();
CtClass simple = factory.Class().get("Simple");
CtMethod method = core.createMethod();
method.addModifier(ModifierKind.PUBLIC);
method.setType(factory.Type().integerPrimitiveType());
method.setSimpleName("m");
CtBlock block = core.createBlock();
CtReturn aReturn = core.createReturn();
CtBinaryOperator binaryOperator = code.createBinaryOperator(code.createLiteral(10), code.createLiteral(32), BinaryOperatorKind.PLUS);
aReturn.setReturnedExpression(binaryOperator);
// return 10 + 32;
block.addStatement(aReturn);
method.setBody(block);
simple.addMethod(method);
launcher.getModelBuilder().compile();
final URLClassLoader urlClassLoader = new URLClassLoader(new URL[] { outputBinDirectory.toURL() });
Class<?> aClass = urlClassLoader.loadClass("Simple");
Method m = aClass.getMethod("m");
Assert.assertEquals(42, m.invoke(aClass.newInstance()));
}
use of spoon.reflect.factory.CodeFactory in project spoon by INRIA.
the class LiteralTest method testFactoryLiternal.
@Test
public void testFactoryLiternal() {
Launcher runLaunch = new Launcher();
Factory factory = runLaunch.getFactory();
CodeFactory code = factory.Code();
CtLiteral literal = code.createLiteral(1);
assertEquals(1, literal.getValue());
assertEquals(factory.Type().integerPrimitiveType(), literal.getType());
literal = code.createLiteral(new Integer(1));
assertEquals(1, literal.getValue());
assertEquals(factory.Type().integerPrimitiveType(), literal.getType());
literal = code.createLiteral(1.0);
assertEquals(1.0, literal.getValue());
assertEquals(factory.Type().doublePrimitiveType(), literal.getType());
literal = code.createLiteral("literal");
assertEquals("literal", literal.getValue());
assertEquals(factory.Type().stringType(), literal.getType());
}
Aggregations