欢迎来到我的的博客园,祝大家学有所成,早点实现自己的人生理想。

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();
        }
    }
}

 

三、运行结果

posted @ 2018-04-18 12:02  宋兴柱  阅读(784)  评论(0编辑  收藏  举报