See this headline, if you think you can really automatically generate it, then you're too naive.
What I want to introduce here is to use the template to generate the code we need
First, the template
First of all, the template, Common Java templates are: Freemarker, Velocity, Jamon, Jbyte and so on.
Unfamiliar can Baidu under, in fact, I do not know much, haha.
Second, the principle
It's actually using templates to populate the data and get the code we need. That is: output = template + data
Third, examples
The instance uses Freemarker to do so you need to import the Freemarker jar package first
Suppose we need to generate a Java bean automatically, then our template (FORMBEAN.FTL) might look like this
Public class${beanname?Cap_first} Form {< #list params as param>Private${param.paramtype} ${param.paramname}; Public voidSet${param.paramname?Cap_first} (${param.paramtype} ${param.paramname}) { This. ${param.paramname} =${param.paramname}; } Public${param.paramtype} get${param.paramname?Cap_first} (){ return This. ${param.paramname}; } </#list >}
One of the Cap_first's role is to capitalize the first letter, these are the methods in FTL, can Baidu Google's
Next, assemble the data, generate the file demo
//Assemble Datamap<string, object> formbeanmap =NewHashmap<string, object>(); Formbeanmap.put ("Beanname", "Testbean"); List<map<string, string>> paramslist =NewArraylist<map<string, string>>(); for(inti = 0; I < 4; i++) {Map<string, string> tmpparammap =NewHashmap<string, string>(); Tmpparammap.put ("Paramtype", "String"); Tmpparammap.put ("ParamName", "param" +i); Paramslist.add (TMPPARAMMAP);} Formbeanmap.put ("Params", paramslist); freemarker.template.Configuration config=Newfreemarker.template.Configuration (); Config.setobjectwrapper (NewDefaultobjectwrapper ()); Template formbeantemplate= Config.gettemplate ("FORMBEAN.FTL", "UTF-8"); Writer out=NewBufferedWriter (NewOutputStreamWriter (NewFileOutputStream ("C:\\testbeanform.java"), "UTF-8") ; Formbeantemplate.process (Formbeanmap, out); Out.flush (); Out.close () ;
After executing the formbeantemplate.process, you can generate code based on the template and the data.
Java Auto-generated code