How to create java pojo

I want to read a properties file and create a pojo from it. where the property key is an instance variable with getters and setters. and the property value is the data type of the instance variable. the input will be something like this

className=Temp
packageName=com.temp
name=java.lang.String

      

will be

package com.temp;
import java.lang.String;
class Temp{
  private String name

  //getters and setters
}

      

that this is the easiest way to do it. Should I create a file and write to it. Or is there a better way.

+3


source to share


4 answers


I generated a Java file somehow using Apache Velocity , you can take a look at it.



In short, you create a file template and then use it to generate what you want.

+2


source


Java Reflection is specifically for creating objects on the fly. Be mindful of the performance you are taking though.



Reflection is commonly used by programs that require the ability to examine or modify the behavior of the runtime of applications running in the Java Virtual Machine. This is a relatively advanced feature and should only be used by developers who have a good understanding of the basics of the language. With this caveat in mind, reflection is a powerful technique and allows applications to perform operations that would otherwise be impossible.

+1


source


Properties properties = new Properties();
try  
{
    FileWriter outFile = new FileWriter("filename.java");
    properties.load(new FileInputStream("filename.properties"));

    outFile.print("package ");
    outFile.println(properties.getProperty("packageName"));

    outFile.print("import ");
    outFile.println(properties.getProperty("name"));

    outFile.print("public class ");
    outFile.println(properties.getProperty("className"));
    outFile.println("{");
    // ... 
    outFile.println("}");

    outFile.close();
}  
catch (IOException e)  
{
    // handle the error 
}

      

+1


source


check http://codemodel.java.net/ if you want to create more complex classes.

+1


source







All Articles