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

时间:2018-05-22 09:57:32

标签: java class dynamic dynamic-class-creation

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

  1. 名为mod_login的新文件夹
  2. 在mod_login内部创建从模板创建的java类文件
  3. 如果模板是

    IF OBJECT_ID('tempdb..#Transactions') IS NOT NULL
        DROP TABLE #Transactions
    
    CREATE TABLE #Transactions (
        ClientCode VARCHAR(100),
        Date DATE)
    
    INSERT INTO #Transactions (
        ClientCode,
        Date)
    VALUES
        ('DL2', '2016-04-18'),
        ('DL2', '2016-04-19'),
        ('DL2', '2016-04-26'),
    
        ('E19', '2016-01-01'),
        ('E19', '2016-01-11'),
        ('E19', '2016-01-12')
    
    
    ;WITH DayDifferences AS
    (
        SELECT
            T.ClientCode,
            T.Date,
            DayDifference = DATEDIFF(
                DAY,
                LAG(T.Date) OVER (PARTITION BY T.ClientCode ORDER BY T.Date ASC),
                T.Date)
        FROM
            #Transactions AS T
    )
    SELECT
        D.ClientCode,
        AverageDayDifference = AVG(ISNULL(CONVERT(FLOAT, D.DayDifference), 0))
    FROM
        DayDifferences AS D
    GROUP BY
        D.ClientCode
    

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

    class Name extends Blah implement Blah {
    
        private createdInt;
    
        private int getCreatedInt() {
            return createdInt;
        }
    
    }
    

    试图用groovy去做,但找不到任何有用的东西。

    P.S。它不应该在运行时发生,它更像是一个帮助器,只用一个按钮来实例化这些模块,而不是输入它们

2 个答案:

答案 0 :(得分:6)

可以帮助您的工作示例。

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());
 }
}

答案 1 :(得分:0)

您只需要在动态创建文件的方法中定义2个变量。

的className &安培; propertyName的

现在使用这些来创建扩展名为.java的文件,并按原样从模板中写入文本。对于className和propertyName生成逻辑,请使用上面的变量。

如果您想创建多个此类文件,请使用className&amp;列表中的propertyName并运行forloop。