动态编译Java文件并加载对象

动态编译Java文件并加载对象

摘要

动态编译Java文件并加载对象

动态编译Java文件并加载对象

动态构造一个Calc对象,并调用对象上的sum方法.

package test_base;

import com.itranswarp.compiler.JavaStringCompiler;
import org.nutz.lang.Mirror;

import java.util.Map;

/**
 * Created by zhu on 17-8-5.
 */
public class Test02 {


    /**
     * java 脚本引擎  示例
     *
     * @param args
     */
    public static void main(String[] args) {


        try {
            JavaStringCompiler compiler = new JavaStringCompiler();

            //1个java文件里面可能有多个类,但是只能 有1个public的类
            Map<String, byte[]> results = compiler.compile("Calc.java", JAVA_SOURCE_CODE);
            Class<?> clazz = compiler.loadClass("net.javablog.ut.Calc", results);


            Object calc = clazz.newInstance();

            //执行 1+2  , 最终会输出3
            System.out.println(Mirror.me(clazz).invoke(calc, "sum", 1, 2));


        } catch (Exception e) {

        }


    }

    static final String JAVA_SOURCE_CODE =
            "package net.javablog.ut;" +
                    "public class Calc {" +
                    "" +
                    "    public int sum(int a, int b) {" +
                    "        return a + b;" +
                    "    }" +
                    "" +
                    "} ";


}

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>net.javablog</groupId>
    <artifactId>basejava</artifactId>
    <version>1.0-SNAPSHOT</version>


    <dependencies>

        <dependency>
            <groupId>com.itranswarp</groupId>
            <artifactId>compiler</artifactId>
            <version>1.0</version>
        </dependency>

        <dependency>
            <groupId>org.nutz</groupId>
            <artifactId>nutz</artifactId>
            <version>1.r.62</version>
        </dependency>

    </dependencies>

</project>

demo地址

https://github.com/daodaovps/testJavaCompile