java - 如何动态创建 Java 类/es 文件?

标签 java class dynamic dynamic-class-creation

我需要一种方法来为 ex 运行 java 方法。 createModule("登录") 并作为输出:

  1. 名为 mod_login 的新文件夹
  2. 在从模板创建的 mod_login java 类文件中

如果模板是

class Name extends Blah implement Blah {

    private createdInt;

    private int getCreatedInt() {
        return createdInt;
    }

}

作为返回,我想获得一个动态创建的类:

 class Login extends Blah implement Blah {

    private loginInt;

    private int getLoginInt() {
        return loginInt;
    }
}

试图研究 groovy 来做到这一点,但找不到任何有用的东西。

附言它不应该在运行时发生,它更像是一个助手,只需一个按钮即可实例化这些模块,而不是键入它们

最佳答案

对您有帮助的工作示例。

import java.io.File;
import java.io.FileWriter;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Arrays;

import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.StandardLocation;
import javax.tools.ToolProvider;

public class HelloWorld {

public static void main(String[] args) throws Exception {

    // create an empty source file
    File sourceFile = File.createTempFile("Hello", ".java");
    sourceFile.deleteOnExit();

    // generate the source code, using the source filename as the class name
    String classname = sourceFile.getName().split("\\.")[0];
    String sourceCode = "public class " + classname + "{ public void hello() { System.out.print(\"Hello world\");}}";

    // write the source code into the source file
    FileWriter writer = new FileWriter(sourceFile);
    writer.write(sourceCode);
    writer.close();

    // compile the source file
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    File parentDirectory = sourceFile.getParentFile();
    fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(parentDirectory));
    Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(Arrays.asList(sourceFile));
    compiler.getTask(null, fileManager, null, null, null, compilationUnits).call();
    fileManager.close();

    // load the compiled class
    URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { parentDirectory.toURI().toURL() });
    Class<?> helloClass = classLoader.loadClass(classname);

    // call a method on the loaded class
    Method helloMethod = helloClass.getDeclaredMethod("hello");
    helloMethod.invoke(helloClass.newInstance());
 }
}

关于java - 如何动态创建 Java 类/es 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50464807/

相关文章:

javascript - typescript 错误 "Cannot find name"

c++ - 读取文件时两次获得相同的输出

c++ - 类名或命名空间的问题

c# - 具有多个/未知条件的动态 linq 查询

java - 我正在实例化从 Java (J2ObjC) 转译的 Swift 非 ARC Objective-C 类,它是否泄漏安全?

java - 用于存储键值对的轻量级数据库类库

java - Spring Data JPA - for循环不保存实体

java - 如何让 JTextArea 完全填满 JPanel?

使用反射在运行时进行 C# 类型转换

excel - Python - XlsxWriter : Referring to columns by column name, 不是列字母(硬编码与动态变量)