JAVA动态编译辅助类
一、场景
平时我们学学用到在JVM运行时,动态编译.java的源代码情况,比如作为灵活的配置文件。这时候就要用到动态编译,参考下列。
二、类内容
1、引入依赖:
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
2、编写基本类,让它继承 SimpleJavaFileObject 类。
package com.songxingzhu.utils.compile; import javax.tools.SimpleJavaFileObject;
import java.net.URI; public class JavaSourceFromCodeString extends SimpleJavaFileObject {
final String code; public JavaSourceFromCodeString(String name, String code) {
super(URI.create("string:///" + name.replace('.', '/') + Kind.SOURCE.extension), Kind.SOURCE);
this.code = code;
} public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return this.code;
}
}
2、编写工具类
package com.songxingzhu.utils.context; import java.io.File; public class AppContext {
public static String baseDirectory() {
try {
String path = ClassLoader.getSystemResource("").getPath();
if (path==null||"".equal(path))
return getProjectPath();
return path;
} catch (Exception ignored) {
}
return getProjectPath();
} private static String getProjectPath() {
java.net.URL url = AppContext.class.getProtectionDomain().getCodeSource()
.getLocation();
String filePath = null;
try {
filePath = java.net.URLDecoder.decode(url.getPath(), "UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
if (filePath.endsWith(".jar"))
filePath = filePath.substring(0, filePath.lastIndexOf(File.separatorChar) + 1);
java.io.File file = new java.io.File(filePath);
filePath = file.getAbsolutePath();
return filePath;
}
}
package com.songxingzhu.utils.compile; import org.apache.commons.io.FileUtils;
import com.songxingzhu.utils.context.AppContext; import javax.tools.JavaCompiler;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import javax.tools.ToolProvider;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List; public class ClassBuilder { public static Class<?> buildClass(String fullClassName, String codeFilePath) throws IOException, ClassNotFoundException { return buildClass(fullClassName, codeFilePath, "UTF-8", AppContext.baseDirectory());
} public static Class<?> buildClass(String fullClassName, String codeFilePath, String charsetName, String buildOutput) throws IOException, ClassNotFoundException {
try {
String code = FileUtils.readFileToString(FileUtils.getFile(codeFilePath), charsetName);
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
JavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
List<JavaFileObject> files = new ArrayList<>();
files.add(new JavaSourceFromCodeString(fullClassName, code));
List<String> options = new ArrayList<>();
options.add("-classpath");
StringBuilder sb = new StringBuilder();
URLClassLoader urlClassLoader = (URLClassLoader) Thread.currentThread().getContextClassLoader();
for (URL url : urlClassLoader.getURLs()) {
sb.append(url.getFile()).append(File.pathSeparator);
}
options.add(sb.toString());
options.add("-d");
options.add(buildOutput);
// execute the compiler
boolean isok = compiler.getTask(null, fileManager, null, options, null, files).call();
if (isok) {
File root = new File(buildOutput);
if (!root.exists()) root.mkdirs();
URL[] urls = new URL[]{root.toURI().toURL()};
ClassLoader classLoader = ClassBuilder.class.getClassLoader();
Class<?> clazz = Class.forName(fullClassName, true, classLoader);
return clazz;
}
return null;
} catch (Exception ex) {
throw ex;
}
}
}
JAVA动态编译辅助类的更多相关文章
- java动态编译笔记
1 前言 Java的动态编译知识,真真在实际开发中并不是经常遇到.但是学习java动态编译有助于我们从更深一层次去了解java.对掌握jdk的动态代理模式,这样我们在学习其他一些开源框架的时候就能够知 ...
- java动态编译 (java在线执行代码后端实现原理)(二)
在上一篇java动态编译 (java在线执行代码后端实现原理(一))文章中实现了 字符串编译成字节码,然后通过反射来运行代码的demo.这一篇文章提供一个如何防止死循环的代码占用cpu的问题. 思路: ...
- java动态编译 (java在线执行代码后端实现原理)
需求:要实现一个web网页中输入java代码,然后能知道编译结果以及执行结果 类似于菜鸟java在线工具的效果:https://c.runoob.com/compile/10 刚开始从什么概念都没有到 ...
- Java动态编译技术原理
这里介绍Java动态编译技术原理! 编译,一般来说就是将源代码转换成机器码的过程,比如在C语言中中,将C语言源代码编译成a.out,,但是在Java中的理解可能有点不同,编译指的是将java 源代码转 ...
- Java 动态编译--DynamicCompiler
java 动态编译自己写过程的机会比较少,记录一下: package com.xzlf.dynamicCompile; import java.io.IOException; import java. ...
- (转载)JAVA动态编译--字节代码的操纵
在一般的Java应用开发过程中,开发人员使用Java的方式比较简单.打开惯用的IDE,编写Java源代码,再利用IDE提供的功能直接运行Java 程序就可以了.这种开发模式背后的过程是:开发人员编写的 ...
- Java动态编译
程序产生过程 下图展示了从源代码到可运行程序的过程,正常情况下先编译(明文源码到字节码),后执行(JVM加载字节码,获得类模板,实例化,方法使用).本文来探索下当程序已经开始执行,但在.class甚至 ...
- java动态编译类文件并加载到内存中
如果你想在动态编译并加载了class后,能够用hibernate的数据访问接口以面向对象的方式来操作该class类,请参考这篇博文-http://www.cnblogs.com/anai/p/4270 ...
- Java 动态编译组件 & 类动态加载
1.JDK6 动态编译组件 Java SE 6 之后自身集成了运行时编译的组件:javax.tools,存放在 tools.jar 包里,可以实现 Java 源代码编译,帮助扩展静态应用程序.该包中提 ...
随机推荐
- Windows Phone本地数据库(SQLCE):10、创建数据库(翻译) (转)
这是“windows phone mango本地数据库(sqlce)”系列短片文章的第十篇. 为了让你开始在Windows Phone Mango中使用数据库,这一系列短片文章将覆盖所有你需要知道的知 ...
- UnityEngine.Time类属性解析
UnityEngine.Time类包含的属性: public static int captureFramerate { get; set; } public static float deltaTi ...
- Lua调用C++时打印堆栈信息
公司的手游项目,使用的是基于cocos2d-x绑lua的解决方案(参数quick-x的绑定),虽然使用了lua进行开发,更新很爽了,但是崩溃依然较为严重,从后台查看崩溃日志时,基本上只能靠" ...
- Java并发编程的艺术(五)——中断
什么是中断? 在Java中没有办法立即停止一条线程,然而停止线程却显得尤为重要,如取消一个耗时操作.因此,Java提供了一种用于停止线程的机制——中断. 中断只是一种协作机制,Java没有给中断增加任 ...
- Eclipse with ADT的安装和使用
我们从安卓官方网站下载下来的eclipse是捆绑好了ADT的,所以不用自己安装插件. 我现在在这个目录下简历一个空的文件夹--virtual,用来来存放虚拟机. 然后,在我的电脑上右键->属性, ...
- 关于MySQL的行转列的简单应用(二)---group函数
MySQL的行转列.列转行.连接字符串 concat.concat_ws.group_concat函数用法使用方法:CONCAT(str1,str2,…) 返回结果为连接参数产生的字符串.如有任何一 ...
- [转]thinkphp在iis下的rewrite伪静态的配置方法
From : http://code-tech.diandian.com/post/2012-11-12/40042151797 首先你要安装IIS下的rewrite组建,下载地址:Rewrite.z ...
- hdu-4466-Triangle 数学题
题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=4466 题目意思: 一根长为N的木棒,长度分成若干个三角形,使得任意两个三角形都相似.对应顺序三角形全 ...
- go语言之进阶篇 channel介绍
1.channel介绍 和map类似,channel也一个对应make创建的底层数据结构的引用. 当我们复制一个channel或用于函数参数传递时,我们只是拷贝了一个channel引用,因此调用者何被 ...
- 阅读日志: 微信小程序的风口只有一天?
原文地址: 小程序的风口只有一天?难道我们用的是假的小程序 http://xudanei.baijia.baidu.com/article/755506 原文摘要: #,小程序的趋势,从1月10日至1 ...