Skip to content

Commit d5a9159

Browse files
author
yongjie.zhang
committed
动态编译
1 parent 98fef09 commit d5a9159

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<module type="JAVA_MODULE" version="4">
3+
<component name="NewModuleRootManager" inherit-compiler-output="true">
4+
<exclude-output />
5+
<content url="file://$MODULE_DIR$">
6+
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
7+
</content>
8+
<orderEntry type="inheritedJdk" />
9+
<orderEntry type="sourceFolder" forTests="false" />
10+
</component>
11+
</module>
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
package com.zyj.compile;
2+
3+
import org.omg.SendingContext.RunTime;
4+
5+
import javax.tools.JavaCompiler;
6+
import javax.tools.ToolProvider;
7+
import java.io.BufferedReader;
8+
import java.io.IOException;
9+
import java.io.InputStream;
10+
import java.io.InputStreamReader;
11+
import java.net.URL;
12+
import java.net.URLClassLoader;
13+
14+
/**
15+
* 版权声明:CopyRight (c) 2018 ucarinc. All Rights Reserved.
16+
*
17+
* @author : 张勇杰
18+
* @date : 2018/11/26 14:58
19+
* @Version : v1.0
20+
* @description
21+
**/
22+
@SuppressWarnings("all")
23+
public class Demo01 {
24+
public static void main(String[] args) throws IOException {
25+
26+
//通过IO流操作,将字符串存储成一个临时文件(Hi.java),然后调用动态编译方法
27+
String str = "public class hi{public static void main(String[] args){System.out.println(\"hi world\");}}";
28+
29+
30+
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
31+
int result = compiler.run(null,null,null,"C:/Users/张勇杰/Desktop/helloworld.java");
32+
System.out.println(result == 0?"编译成功":"编译失败");
33+
34+
//通过Runtime调用执行类
35+
/*Runtime run = Runtime.getRuntime();
36+
37+
Process process = run.exec("java -cp C:/Users/张勇杰/Desktop/ helloworld");
38+
39+
InputStream in = process.getInputStream();
40+
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
41+
String info="";
42+
while((info=reader.readLine())!=null){
43+
System.out.println(info);
44+
}*/
45+
46+
try{
47+
URL[] urls = new URL[]{new URL("file:/"+"C:/Users/张勇杰/Desktop/")};
48+
URLClassLoader loader = new URLClassLoader(urls);
49+
Class c = loader.loadClass("helloworld");
50+
//调用加载类的main方法
51+
//参数一定要强转成object,由于可变参数是java5.0以后才有,会造成参数不匹配的问题
52+
c.getMethod("main",String[].class).invoke(null,(Object) new String[]{});
53+
}catch (Exception e){
54+
e.printStackTrace();
55+
56+
}
57+
}
58+
}

0 commit comments

Comments
 (0)