一、引用库
pom文件中申明如下:
junit junit 4.12 test com.github.henryhuang dynamiccompiler 0.1.0
二、测试代码
import com.github.henryhuang.dynamiccompiler.ClassGenerator;import org.junit.Test;import java.lang.reflect.Method;public class HelloTest { @Test public void test() { ClassGenerator builder = new ClassGenerator("."); try { Class testclass = builder.generate("TestClass", "" + "public class TestClass{" + " public static String execute(String[] args){" + " System.out.println(\"Test!\"); " + " return args[0];" + " }" + "}"); Method method = testclass.getMethod("execute", String[].class); for (int i = 0; i < 100; i++) { String[] params = {"宋柱柱" + i, "def"}; Object result = method.invoke(null, (Object) params); System.out.println("result:" + result); } } catch (Exception ex) { ex.printStackTrace(); } }}
三、运行结果