Created
September 18, 2017 05:32
-
-
Save komamitsu/c130b023700ba41b4d0cf01776c2d3b4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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