Skip to content

Instantly share code, notes, and snippets.

@komamitsu
Created September 18, 2017 05:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save komamitsu/c130b023700ba41b4d0cf01776c2d3b4 to your computer and use it in GitHub Desktop.
Save komamitsu/c130b023700ba41b4d0cf01776c2d3b4 to your computer and use it in GitHub Desktop.
package org.komamitsu.test;
import org.codehaus.commons.compiler.CompilerFactoryFactory;
import org.codehaus.commons.compiler.IClassBodyEvaluator;
import java.lang.reflect.Method;
public class JaninoExample
{
public int add(int a, int b)
{
System.out.println("Hello: " + (a + b));
return a + b;
}
public static void main(String args[])
throws Exception
{
new JaninoExample().run();
}
public void run()
throws Exception
{
IClassBodyEvaluator cbe = CompilerFactoryFactory.getDefaultCompilerFactory().newClassBodyEvaluator();
cbe.cook(
"public static int newAdd(org.komamitsu.test.JaninoExample x, int a, int b)\n" +
"{\n" +
" System.out.println(a);\n" +
" return x.add(a, b);\n" +
"}\n"
);
Class<? extends JaninoExample> clazz = (Class<? extends JaninoExample>) cbe.getClazz();
Method newAdd = clazz.getMethod("newAdd", JaninoExample.class, int.class, int.class);
System.out.println(newAdd.invoke(null, this, 12, 42));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment