一、引用库
pom文件中申明如下:
<dependencies> <!-- https://mvnrepository.com/artifact/junit/junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/com.github.henryhuang/dynamiccompiler --> <dependency> <groupId>com.github.henryhuang</groupId> <artifactId>dynamiccompiler</artifactId> <version>0.1.0</version> </dependency> </dependencies>
二、测试代码
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(); } } }
三、运行结果