package cn.hutool.script.test;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import java.io.Writer;
import java.lang.reflect.Method;
import java.net.URLClassLoader;
import java.io.File;
import java.io.FileWriter;
import java.net.URL;
/**
* hutool-v5-master
*
* @author : Mr. Lee
* @date : 2024-04-24 17:47
**/
public class DynamicCode {
public static void main(String[] args) throws Exception {
// 输入的Java代码
String inputCode = "import cn.hutool.script.test.domain.Cunstom;\n" +
"import java.text.SimpleDateFormat;\n" +
"import java.util.Date;\n" +
"\n" +
"public class DynamicClass {\n" +
" SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy年MM月dd日\");\n" +
" public Cunstom printMessage(String name) {\n" +
" Cunstom cunstom = new Cunstom();\n" +
" cunstom.setName(name);\n" +
" cunstom.setIden(\"62042219950201966\");\n" +
" cunstom.setCreateTime(sdf.format(new Date()));\n" +
" return cunstom;\n" +
" }\n" +
"}";
// 将输入的Java代码写入到一个临时文件中
File javaFile = new File("DynamicClass.java");
Writer writer = new FileWriter(javaFile);
writer.write(inputCode);
writer.close();
// 获取Java编译器
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
// 编译Java代码
compiler.run(null, null, null, javaFile.getPath());
// 使用URLClassLoader加载动态编译生成的类
URLClassLoader classLoader = URLClassLoader.newInstance(new URL[]{new File("").toURI().toURL()});
Class<?> dynamicClass = Class.forName("DynamicClass", true, classLoader);
// 实例化动态生成的类
Object dynamicObject = dynamicClass.getDeclaredConstructor().newInstance();
// 调用动态生成的类的方法
Method method = dynamicClass.getDeclaredMethod("printMessage", String.class);
// 如果方法带有多个参数,可以在方法调用时传入参数值
String name = "张三"; // 例如,这里传入姓名参数
Object result = method.invoke(dynamicObject, name);
// 输出方法的返回结果
System.out.println(result);
}
}
Java 如何动态加载执行类,动态加载类方法
最新推荐文章于 2024-08-30 13:20:15 发布