1 Star 0 Fork 3

yasepix / JCompiler

forked from 蒋固金 / JCompiler 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
README.md 2.41 KB
一键复制 编辑 原始数据 按行查看 历史
蒋固金 提交于 2021-03-28 09:07 . 1

第一部分 简介

JCompiler是用Java 编写的用来将Java源代码动态编译为字节码的辅助工具,开发者可以动态生成源代码并在内存中将其进行编译并获得编译后的类对象。

第二部分 开始使用

使用JCompiler可以直接下载源代码编译或者下载已经编译的jar文件,如果您是使用maven来构建项目,也可以直接在pom.xml中添加JCompiler的坐标:

Maven central

<!-- http://mvnrepository.com/artifact/com.jianggujin/JCompiler -->
<dependency>
    <groupId>com.jianggujin</groupId>
    <artifactId>JCompiler</artifactId>
    <version>最新版本</version>
</dependency>

最新的版本可以从Maven仓库或者码云获取。

如果使用快照SNAPSHOT版本需要添加仓库,且版本号为快照版本 点击查看最新快照版本号

<repository>
    <id>snapshots</id>
    <url>https://oss.sonatype.org/content/repositories/snapshots/</url>
</repository>

一个例子:

假设我们有一个接口Parent,其代码如下:

public interface Parent {
    void say();
}

定义接口是为了动态生成的类对象方便调用,也可以通过其他方式,此处仅仅是为了演示

我们可以准备一个代码片段如下:

package com.jianggujin.compiler.test;
public class Test implements com.jianggujin.compiler.test.CompileTest.Parent {
    public void say() {
        System.out.println("this is dynamic compile class.");
    }
}

此处的代码片段为字符串变量content的值,并非直接编写的源代码

然后我们仅需要简单的几行代码即可实现对上面的代码片段进行编译执行:

JMemoryJavaCompiler compiler = new JMemoryJavaCompiler();
JCompileResult result = compiler.compile(content);
System.out.println(result);
if (result.isSuccess()) {
    ((Parent) result.newInstance()).say();
}
compiler.close();

完整代码参见单元测试代码:src/test/java/com/jianggujin/compiler/test/CompileTest.java

马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Java
1
https://gitee.com/yasepix/JCompiler.git
git@gitee.com:yasepix/JCompiler.git
yasepix
JCompiler
JCompiler
master

搜索帮助

344bd9b3 5694891 D2dac590 5694891