Dynamically create table and java classes at runtime

前端 未结 3 939
Happy的楠姐
Happy的楠姐 2021-01-06 12:18

I have a requirement in my application. My tables wont be defined beforehand.For Example,if the user creates a form by name Student,and adds its attributes like name,roll n

3条回答
  •  清歌不尽
    2021-01-06 13:05

    last week I was looking for same solution and then I got idea from com.sun.tools.javac.Main.compile class, you create the Entity class using java IO and compile using java tools, for this you need tools.jar to locate on CLASS_PATH, now I am looking for run time hibernate mapping without restart. some one was saying in the post regarding to this type of requirement that "but it's not clear why would you want to do something like that" answer is this requirement is for CMS(Content Management System). and I am doing the same. code is as below.

     public static void createClass()
    {
    String methodName=“execute”;
    String parameterName=“strParam”;
    try{
    //Creates DynamicTestClass.java file
    FileWriter fileWriter=new FileWriter(fileName,false);
    fileWriter.write(“public class “+ className +” {\n”);
    fileWriter.write(“public String “+methodName +“(String “+parameterName+“) {\n”);
    fileWriter.write(“System.out.println(\” Testing\”);\n”);
    fileWriter.write(“return “+parameterName +“+ \” is dumb\”;\n }\n}”);
    fileWriter.flush();
    fileWriter.close();
    
    String[] source = { new String(fileName) };
    com.sun.tools.javac.Main.compile(source);
    }
    

提交回复
热议问题