package com.byzh;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import java.io.File;
import java.io.FileOutputStream;
import java.lang.reflect.Method;
/**
* 动态生成class文件
*/
public class DynamicGeneratorClass {
public static void generator() throws Exception {
//动态生成Java文件,保存文件到磁盘,动态编译成class文件
String helloWorldJava = "package com.byzh;public class HelloWorld {" + " public String sayHello(String name) {return \"hello :\" + name;}}";
String filePath = Class.class.getResource("/").getPath() + "com/byzh/HelloWorld.java";
System.out.println(filePath);
FileOutputStream fos = new FileOutputStream(new File(filePath));
fos.write(helloWorldJava.getBytes());
fos.close();
//动态编译生成的java文件
JavaCompiler cm = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager sm = cm.getStandardFileManager(null, null, null);
Iterable<? extends JavaFileObject> javaFileObjects = sm.getJavaFileObjects(filePath);
JavaCompiler.CompilationTask task = cm.getTask(null, sm, null, null, null, javaFileObjects);
task.call();
sm.close();
}
public static void main(String[] args) throws Exception {
//自动生成并编译类
DynamicGeneratorClass.generator();
//自定义类加载器加载类
DynamicClassLoader dcl = new DynamicClassLoader();
Class c = dcl.findClass("com.byzh.HelloWorld");
Method sayHello = c.getMethod("sayHello", new Class[]{String.class});
System.out.println(sayHello.invoke(c.newInstance(), "world......"));
}
}
JDK-自动生成JAVA类并编译加载执行
最新推荐文章于 2024-09-18 17:13:27 发布