score:70
Sun provides an API called CodeModel for generating Java source files using an API. It's not the easiest thing to get information on, but it's there and it works extremely well.
The easiest way to get hold of it is as part of the JAXB 2 RI - the XJC schema-to-java generator uses CodeModel to generate its java source, and it's part of the XJC jars. You can use it just for the CodeModel.
Grab it from http://codemodel.java.net/
score:0
It really depends on what you are trying to do. Code generation is a topic within itself. Without a specific use-case, I suggest looking at velocity code generation/template library. Also, if you are doing the code generation offline, I would suggest using something like ArgoUML to go from UML diagram/Object model to Java code.
score:0
Exemple : 1/
private JFieldVar generatedField;
2/
String className = "class name";
/* package name */
JPackage jp = jCodeModel._package("package name ");
/* class name */
JDefinedClass jclass = jp._class(className);
/* add comment */
JDocComment jDocComment = jclass.javadoc();
jDocComment.add("By AUTOMAT D.I.T tools : " + new Date() +" => " + className);
// génération des getter & setter & attribues
// create attribue
this.generatedField = jclass.field(JMod.PRIVATE, Integer.class)
, "attribue name ");
// getter
JMethod getter = jclass.method(JMod.PUBLIC, Integer.class)
, "attribue name ");
getter.body()._return(this.generatedField);
// setter
JMethod setter = jclass.method(JMod.PUBLIC, Integer.class)
,"attribue name ");
// create setter paramétre
JVar setParam = setter.param(getTypeDetailsForCodeModel(Integer.class,"param name");
// affectation ( this.param = setParam )
setter.body().assign(JExpr._this().ref(this.generatedField), setParam);
jCodeModel.build(new File("path c://javaSrc//"));
score:0
Here is a JSON-to-POJO project that looks interesting:
score:1
score:1
I was doing it myself for a mock generator tool. It's a very simple task, even if you need to follow Sun formatting guidelines. I bet you'd finish the code that does it faster then you found something that fits your goal on the Internet.
You've basically outlined the API yourself. Just fill it with the actual code now!
score:1
There is also StringTemplate. It is by the author of ANTLR and is quite powerful.
score:1
There is new project write-it-once. Template based code generator. You write custom template using Groovy, and generate file depending on java reflections. It's the simplest way to generate any file. You can make getters/settest/toString by generating AspectJ files, SQL based on JPA annotations, inserts / updates based on enums and so on.
Template example:
package ${cls.package.name};
public class ${cls.shortName}Builder {
public static ${cls.name}Builder builder() {
return new ${cls.name}Builder();
}
<% for(field in cls.fields) {%>
private ${field.type.name} ${field.name};
<% } %>
<% for(field in cls.fields) {%>
public ${cls.name}Builder ${field.name}(${field.type.name} ${field.name}) {
this.${field.name} = ${field.name};
return this;
}
<% } %>
public ${cls.name} build() {
final ${cls.name} data = new ${cls.name}();
<% for(field in cls.fields) {%>
data.${field.setter.name}(this.${field.name});
<% } %>
return data;
}
}
score:2
I built something that looks very much like your theoretical DSL, called "sourcegen", but technically instead of a util project for an ORM I wrote. The DSL looks like:
@Test
public void testTwoMethods() {
GClass gc = new GClass("foo.bar.Foo");
GMethod hello = gc.getMethod("hello");
hello.arguments("String foo");
hello.setBody("return 'Hi' + foo;");
GMethod goodbye = gc.getMethod("goodbye");
goodbye.arguments("String foo");
goodbye.setBody("return 'Bye' + foo;");
Assert.assertEquals(
Join.lines(new Object[] {
"package foo.bar;",
"",
"public class Foo {",
"",
" public void hello(String foo) {",
" return \"Hi\" + foo;",
" }",
"",
" public void goodbye(String foo) {",
" return \"Bye\" + foo;",
" }",
"",
"}",
"" }),
gc.toCode());
}
https://github.com/stephenh/joist/blob/master/util/src/test/java/joist/sourcegen/GClassTest.java
It also does some neat things like "Auto-organize imports" any FQCNs in parameters/return types, auto-pruning any old files that were not touched in this codegen run, correctly indenting inner classes, etc.
The idea is that generated code should be pretty to look at it, with no warnings (unused imports, etc.), just like the rest of your code. So much generated code is ugly to read...it's horrible.
Anyway, there is not a lot of docs, but I think the API is pretty simple/intuitive. The Maven repo is here if anyone is interested.
score:3
Don't know of a library, but a generic template engine might be all you need. There are a bunch of them, I personally have had good experience with FreeMarker
score:4
The Eclipse JET project can be used to do source generation. I don't think it's API is exactly like the one you described, but every time I've heard of a project doing Java source generation they've used JET or a homegrown tool.
score:9
Another alternative is Eclipse JDT's AST which is good if you need to rewrite arbitrary Java source code rather than just generate source code. (and I believe it can be used independently from eclipse).
score:19
You can use Roaster (https://github.com/forge/roaster) to do code generation.
Here is an example:
JavaClassSource source = Roaster.create(JavaClassSource.class);
source.setName("MyClass").setPublic();
source.addMethod().setName("testMethod").setPrivate().setBody("return null;")
.setReturnType(String.class).addAnnotation(MyAnnotation.class);
System.out.println(source);
will display the following output:
public class MyClass {
private String testMethod() {
return null;
}
}
score:28
Solution found with Eclipse JDT's AST
Thanks, Giles.
For example, with this code:
AST ast = AST.newAST(AST.JLS3);
CompilationUnit cu = ast.newCompilationUnit();
PackageDeclaration p1 = ast.newPackageDeclaration();
p1.setName(ast.newSimpleName("foo"));
cu.setPackage(p1);
ImportDeclaration id = ast.newImportDeclaration();
id.setName(ast.newName(new String[] { "java", "util", "Set" }));
cu.imports().add(id);
TypeDeclaration td = ast.newTypeDeclaration();
td.setName(ast.newSimpleName("Foo"));
TypeParameter tp = ast.newTypeParameter();
tp.setName(ast.newSimpleName("X"));
td.typeParameters().add(tp);
cu.types().add(td);
MethodDeclaration md = ast.newMethodDeclaration();
td.bodyDeclarations().add(md);
Block block = ast.newBlock();
md.setBody(block);
MethodInvocation mi = ast.newMethodInvocation();
mi.setName(ast.newSimpleName("x"));
ExpressionStatement e = ast.newExpressionStatement(mi);
block.statements().add(e);
System.out.println(cu);
I can get this output:
package foo;
import java.util.Set;
class Foo<X> {
void MISSING(){
x();
}
}
score:46
Solution found with CodeModel
Thanks, skaffman.
For example, with this code:
JCodeModel cm = new JCodeModel();
JDefinedClass dc = cm._class("foo.Bar");
JMethod m = dc.method(0, int.class, "foo");
m.body()._return(JExpr.lit(5));
File file = new File("./target/classes");
file.mkdirs();
cm.build(file);
I can get this output:
package foo;
public class Bar {
int foo() {
return 5;
}
}
Source: stackoverflow.com
Related Query
- A Java API to generate Java source files
- java API source files in eclipse
- Auto generate header files for a C source file in an IDE
- Indenting Java source files using Eclipse
- Eclipse Java Debug with missing source files
- Why does Eclipse generate .class file if there is a syntax error in my Java source file?
- Can I configure a resource path that contains java source files in eclipse?
- Replacing a line in a large number of java source files
- Can I have individual Xtend files intermingled with my Java source files in a Spring project?
- Running a script on the Java source files before compiling into bytecode, possible with Eclipse?
- How to edit the existing java source file by using the plugin development API in eclipse?
- eclipse source files are missing after java project is compiled
- Eclipse including Java source code files with class files in WAR
- How to publish a java project source files on GIT?
- Eclipse UML plugin to generate Java Source code
- How to generate Ant and Maven build files for an Eclipse Java project?
- Incrementally compiling java source files
- Is it possible to debug java source files in eclipse
- How to import source files in Java to use in another project
- eclipse unable to generate design view from java source
- Eclipse seems to think the CSS files are Java source code
- In eclipse can we generate main method for a java class from the source
- Java : Debugger is not stopping inside Third Party API class files
- How to Open Existing Java Project Given Entire Source Files
- Can source code files with different encoding coexist in (the same) Java (project in Eclipse)?
- Programmatically compare Two java Source files in Eclipse PDE
- Use JAR file containing only Java source files on Eclipse
- My java source files cannot be commited
- How to generate java source using database details in eclipse
- Android/Eclipse Package Manager: Generate Java files have different icons?
More Query from same tag
- TDGOTCHI in Eclipse - can someone explain how to make it work?
- how to stop AppWidgetProvider autoupdate every 30 min in android
- Operation name must be unique in eclipse
- fill Snipper error
- calling an activity from a fragment class with an onclick method
- What could cause EasyEclipse to terminate with error window?
- Can't make eclipse open even after change eclipse.ini
- Only projects with 'pom' packaging can declare modules
- Codes work in one environment but not another
- Android android-support-v4.jar missmatch
- Android virtual device not listed only in eclipse
- How to add an EMF-model into another EMF-model as a package?
- Scala and Eclipse: Export as Jar File, but cannot find main method
- How can I fix my problem with r.id for android?
- Eclipse oxygen gives syntax error warning in module-info file
- Android ADT: No fragment_main.xml, only activity_main.xml
- wro4j & m2e Eclipse not compiling LESS
- Develop and Debug an Eclipse web app in ONE project
- How do I resolve No qualifying bean for dependency using Java config
- How to show warnings "AdviceDidNotMatch" in eclipse/STS as errors?
- Trying to use a java api loading so file in Android
- BIRT - PDF report creation from a Linux platfrom
- Integrate Stack Overflow into IDEs?
- Android Source build in eclipse failed - Account cannot be resolved to a type
- How to use (or integrate) maven pom.xml with an Eclipse Plugin project for dependency management
- Certification path error when creating Maven project in Eclipse
- Getting Google Places API key for Android
- EL expression is not resolved
- Eclipse in Debug view does not refresh
- Qt 4.7 using Eclipse on windows?