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 源代码编译,帮助扩展静态应用程序.该包中提 ...
随机推荐
- Odoo9发行说明
2015年10月1日,期待已久的Odoo9正式发布.本文是Odoo9正式版发行说明,基于官网资料翻译. 译者: 苏州-微尘原文地址:https://www.odoo.com/page/odoo-9-r ...
- clientX, clientY,offsetX, offsetY,screenX, screenY, x, y
clientX, clientY是鼠标当前相对于网页的位置,当鼠标位于页面左上角时clientX=0, clientY=0: offsetX, offsetY是鼠标当前相对于网页中的某一区域的位置,当 ...
- Android按返回键退出程序但不销毁,程序后台运行,同QQ退出处理方式
@Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BA ...
- FAQ:什么情况下使用 struct ?
问: 什么情况下使用 struct ? 答: 使用 struct 有几个前提(必须全部满足): 容忍 struct 本身的限制,如:不能继承. 值语义. 足够小(<=16字节). 如果 stru ...
- (转载):ASCII,Unicode和UTF-8 编码
UTF-8是Unicode的一种实现方式,也就是它的字节结构有特殊要求,所以我们说一个汉字的范围是0X4E00到0x9FA5,是指unicode值,至于放在utf-8的编码里去就是由三个字节来组织,所 ...
- 关于tomcat和sessionCookieName和SESSION_PARAMETER_NAME以及disableURLRewriting参数原理和使用
关于tomcat和sessionCookieName和SESSION_PARAMETER_NAME以及disableURLRewriting参数 关于session和cookie参考: http:// ...
- android之卸载反馈的功能
感谢这位大神:http://www.eoeandroid.com/thread-317728-1-1.html zip包里面有讲解的试用方法,和如何试用ndk编译的方法,本人亲身试验,确实可用,现做一 ...
- probotuf 标量数值类型
标量数值类型 一个标量消息字段可以含有一个如下的类型--该表格展示了定义于.proto文件中的类型,以及与之对应的.在自动生成的访问类中定义的类型: .proto类型 Java 类型 C++类型 备注 ...
- iOS "directory not found for option '-L/Users/.../Pods/build/Debug-iphoneos"解决方式
问题重述: 在删掉原来工作空间,又一次install pods之后,遇到warning: ld: warning: directory not found for option '-L/Users/. ...
- 修改IP地址的PowerShell
$wmi = Get-WmiObject win32_networkadapterconfiguration -filter "ipenabled = 'true'" $wmi.E ...