动态编译、加载类

package com.crnielsen.tag;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.Arrays;

import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;

public class Test {

public static void main(String args[]) throws Exception {
Runtime run = Runtime.getRuntime();
eval("test....fuck.....");
}

public static void eval(String str) {
// System.out.println(System.getProperty("user.dir"));
String packageName = "cn.wingware";
String className = "Temp";


String s = "package "+packageName+";public class "+className+"{";
s += "public String call(StringBuffer ss){";
s += "System.out.println(\">>>\"+ss);";
s += "return \"sdfsf>>>>>>>>>>>>>>>>>\"+ss.getClass()+\"<<<>>>\"+ss.toString();";
s += "}}";
java.io.File f = new java.io.File("d:\\"+className+".java");
try {
PrintWriter pw = new PrintWriter(f);
pw.println(s);
pw.close();
// 动态编译
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector diagnostics = new DiagnosticCollector();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
Iterable compilationUnits = fileManager.getJavaFileObjectsFromStrings(Arrays.asList(f.getAbsolutePath()));
JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, null, null, compilationUnits);
boolean success = task.call();
fileManager.close();
System.out.println((success) ? "编译成功" : "编译失败");
} catch (Exception e) {
System.out.println("编译错误!");
e.printStackTrace();
}
try {
WingwareClassLoader loader = new WingwareClassLoader();
System.out.println("###"+loader);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] bs = new byte[1024];
InputStream in = new FileInputStream("d:\\"+className+".class");
int length;
while((length=in.read(bs))!=-1){
baos.write(bs, 0, length);
}
baos.flush();
in.close();
bs = baos.toByteArray();
Class<?> cls = loader.loadClass(packageName+"."+className, bs);
Object obj = cls.newInstance();

// 映射call方法
Method call = cls.getMethod("call",StringBuffer.class);
// 执行call方法
System.out.println("返回内容:"+call.invoke(obj,new StringBuffer(str)));
} catch (Exception e) {
e.printStackTrace();
System.out.println("运行错误!");
}

}

}

class WingwareClassLoader extends ClassLoader{

@SuppressWarnings( { "unchecked" }) 
public Class loadClass(String zlass, byte[] bs) throws IOException { 
    Class cNew = super.defineClass(zlass, bs, 0, bs.length); 
    return cNew; 

 

}

你可能感兴趣的:(动态编译,动态加载类)