package com.ruoyi.system.test.code;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class DynamicCodeExecution {
    public static void main(String[] args) {
        String codeToExecute = "System.out.println(\"Hello, World12312!\");";

        try {
            String className = "test";
            String packageName = DynamicCodeExecution.class.getPackage().getName(); // 获取当前类的包名
            String sourceCode = "package " + packageName + ";\n" +
                    "public class " + className + " { public void execute() { " + codeToExecute + " } }";

            // 获取当前包的路径
            Path packagePath = Paths.get("ruoyi-system/src/main/java", packageName.replace(".", "/"));
            // 将源代码写入一个.java文件，保存到当前包下
            Path sourcePath = packagePath.resolve(className + ".java");
            Files.createDirectories(packagePath);
            Files.write(sourcePath, sourceCode.getBytes(), StandardOpenOption.CREATE);

            // 使用Java编译器编译.java文件为.class文件
            Process compileProcess = Runtime.getRuntime().exec("javac " + sourcePath, null, packagePath.toFile());
            compileProcess.waitFor();

            // 创建一个新的ClassLoader以加载编译后的类
            DynamicClassLoader classLoader = new DynamicClassLoader();
            Class<?> dynamicClass = classLoader.loadClass(packageName + "." + className);

            // 在动态生成的类上查找名为"execute"的方法
            dynamicClass.getMethod("execute").invoke(dynamicClass.newInstance());

            // 删除生成的.java和.class文件
            Files.deleteIfExists(sourcePath);
            Files.deleteIfExists(packagePath.resolve(className + ".class"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class DynamicClassLoader extends ClassLoader {
    public Class<?> loadClass(String className) throws ClassNotFoundException {
        return super.findSystemClass(className);
    }
}
