JAVA中动态编译的简单使用
JAVA中动态编译的简单使用
一、引用库
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();
}
}
}
三、运行结果
JAVA中动态编译的简单使用
https://www.dearcloud.cn/2018/04/18/20200310-cnblogs-old-posts/20180418-JAVA中动态编译的简单使用/