In my Java application I have a class Foo
class Foo {
String field1;
String field2;
}
I would like to have some generated code which uses reflection on the fields in this class
(Imaginary template language)
#for each Field $f in Foo.class.getDeclaredFields()
#writeFile $f.java
public #interface $f {
}
The end goal is to have Field1.java and Field2.java with just a simple #interface definition inside each.
Is there a templating language available which could do this generation as part of a Maven build process?
The closest I have been able to find is JET, but this project seems more geared towards generating Java source to be available at runtime, not at compile time. In theory I could probably make this work using AntRun along with several Javac and Java tasks, but it would be cumbersome.
The actual use case which I need this for is generating BindingAnnotations for Google Guice (which will be used in GWT source, so they must exist as .java files at compile time).
I would suggest two options here:
Apache Velocity: it provides a template language looking close to what you describe. Look into it here. You could probably be interested by their engine.
GWTP seems to do something similar to what you are wanting to do. It looks likes they are using annotation processor to perform their code generation. Here is a processor example and their project home is here.
Take a look at Acceleo it is based on XSL Templates to generate source code .
I used it with EMF to generate source code from a Data Model designed by the user.
Related
like:
import com.xxx.utility.*;
class MyClass{
public static void main(String[] args){
MyUtiliy ut = new MyUtiliy();
MyUtility.doAdd(5, 6);
.......
}
}
When put the "." after MyUtiliy, eclipse will tell you all the methods you can use, how does eclipse achieve this?
Does eclipse use the reflection on the fly? (like the answer of this thread? )
The architecture of the eclipse software is describe here, in the section 6.1.2. Java Development Tools (JDT) it briefly describes the incremental build system used. That system would have all the relavent information to populate the autocomplete mechanism.
For the exact mechanism, you would have to look at the eclipse source code.
Yes Eclipse (and any other Java IDEs) uses reflection.
If fact Eclipse uses a ClassLoader for each project's libraries, so it load the classes in jar files, and after that everything is easy, it can get information using reflection.
By the way java IDEs not only use reflection, but also read class debug info, to extract parameter names, and so on.
There is an explanation in this article. Basically the Eclipse Java compiler builds an Abstract Syntax Tree (AST) of your code which lets it find all the information it needs for autocompletion very quickly.
So it is not using reflection for this, rather it is compiling the code in to an internal form for quick access.
When no source code is available (you just have a .class file) it is still possible to construct the part of the AST containing the class methods and types which are needed for completion. This appears to be done by reading the .class files directly rather than using a class loader (org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader)
I'm doing a project which in essence is a way for a user to create macros for very long/repetitive code so they can then put these macros into a their code to increase readability and encourage re-usability.
The project is split up into two areas: an RCP application where the user constructs their macros and saves them to file, and a plugin-in in eclipse where a user can insert a macro.
The RCP application has come along nicely, but now I'm getting to the real bit where I want java to look at a piece of code and at compile time go 'Oh, that piece of code means this'.
For example a user could have created a macro with an identifier macro1 that represents the code System.out.println("Hello World");. They want to use it in their class foo which will look like:
class foo{
//lots of java....
macro1
//lots more java
}
I want the user to run their class, and when Java compiles it replace macro1 with it's value.
I have been looking into this for a while and read up a little bit on JavaCC and looked into Ants Replace Task but I feel I want to go down the road of creating a custom annotation to inform Java that this string below the annotation should be transformed into/replaced by a piece of java code located in a specific text file. Hopefully ending up with something like:
#ExpandMacro
macro1
To me it seems like it could be possible but I don't know if I'm just being too optimistic! :)
Also one of my concerns is how deployable would it be as a plugin? If I create a custom annotation how would I make it available to the user to use?
Any advice/insights would be very helpful!
Edit: I have also looked into Project Lombok which is looks extremely insteresting. But again I'm concerned about deployability because of the amount of setup required for a lombok project.
The best way for doing this is Annotation Processor (something like Lombokg). With JSR 269 Pluggable Annotation Processing API configuration is easy, because jar with processor is autodiscovered.
Look at: http://www.slideshare.net/PolymathicCoder/the-art-of-metaprogramming-in-java page 34
Look at this differently. I think better for you is to use dynamic language (groovy for example). You can write code in Java and run it dynamically with Groovy (without compilation) - because java code is compatible with groovy. So you can simple replace macro1 with what you need and run this code. With groovy you can
write code than looks like java
replace macros with real code
run code without compilation
Links to read:
http://groovy.codehaus.org/Embedding+Groovy
http://groovy.codehaus.org/Differences+from+Java
In Android applications, resources are specified in xml documents, which automatically are built into the R class, readily accessible within the source code as strongly typed.
Is there any way I could use a similar approach for a regular Java desktop application?
What I'd like to accomplish, is both the removal of strings from the code (as a separation of "layers", more or less) and to make it easy to add support for localization, by simply telling the program to choose the xml file corresponding to the desired language.
I've googled around a bit, but the things I'm looking for seem to be drowning in results about parsing or outputting xml, rather than tools utilizing xml to generate code.
Eclipse's message bundle implementation (used by plugins for example) integrates with the Externalize Strings feature and generates both a static class and a resource properties file for your strings:
http://www.eclipse.org/eclipse/platform-core/documents/3.1/message_bundles.html
For this integration to work Eclipse needs to see org.eclipse.osgi.util.NLS on the class path. From memory, the dependencies of the libraries it was available in were a little tricky for the project I used this approach in, so I just got the source and have it as a stand-alone class in my core module (see the comments for more on that).
It provides the type safety you're looking for and the IDE features save a lot of time. I've found no downsides to the approach so far.
Edit: this is actually what ghostbust555 mentioned in the comments, but not clear in that article that this isn't limited to Eclipse plugins and you refer to your resources via static members of a messages class.
I haven't seen any mention of others using this approach with their own applications, but to me it makes complete sense given the IDE integration and type safety.
I'm not sure if this is what you mean but check out internationalization- http://netbeans.org/kb/docs/java/gui-automatic-i18n.html
Are you looking for something that parses XML files and generates Java instances of similar "struct-like" objects, like JAXP, and JAXB?
I came across ResGen which, given resource bundle XML files generates Java files that can be used to access the resources in a type-safe way.
http://eigenbase.sourceforge.net/resgen/
I wanted to use JET (Java Emitter Templates)
in my Netbeans projects, but had to find out that JET
heavily depends on Eclipse libraries.
Is there something similar to JET, but as a standalone project?
Something which is open source and well maintained?
Futhermore, is "code generation" the common term for such tools?
If you are using Maven, you can use JET templates with the maven-jet-plugin.
This seems to be the source code. And here the documentation.
It is not actively maintained but works pretty well and follows the JET spec.
I've used it with templates and skeletons.
It's self contained, doesn't depend on Eclipse, and doesn't introduce any transitive dependencies to your project.
Indeed JET is very tied with Eclipse.
If you want to generate code without Eclipse you should use another solution.
You can choose another template engine like Velocity (https://velocity.apache.org/) or FreeMarker (https://freemarker.apache.org/).
Or you can choose a code generator working by itself independently of any IDE.
For example "Telosys Command Line Interface" : http://www.telosys.org/
From what I know, JET is something like JSP, no?
Java Emitter Templates are very similar to Java Server Pages (JSPs). Both JETs and JSPs use the same syntax, and are compiled to Java behind the scenes. Both are used to separate the responsibility for rendering pages from the model and controller. Both accept objects passed into them as an input argument, both allow inserting string values within code ("expressions"), and allow direct use of Java code to perform loops, declare variable, or perform logical flows ("scriptlets"). Both are good ways of representing the structure of a generated object (web page, Java class, or file) while supporting customization of the details.
JETs differ from JSPs in a few key ways. In a JET, the structure of the markup may be changed to support generating code in different languages. Typically the input to a JET will be a configuration file and not user input (though there is nothing forbidding this). And also typically, JET processing will take place only once for a given workflow. These are not technical limitations, and you may find uses for JETs which are quite different...
ibm.com
Here are a few links to get you started on JSP, if that sounds like what you need:
sun.com
netbeans.org
Look for "template engine" for these types of tools.
A couple you might want to look at:
Apache Velocity (http://velocity.apache.org/)
StringTemplate (http://stringtemplate.org/)
I ended up using ERB (Ruby's template engine).
Works great in Netbeans!
I define custom ant task which generates source files by calling ERB (whose results are placed inside a non-versioned special directory).
The ant task is overriding Netbeans' "-pre-compile" task.
For C#, I have often used CodeSmith and lately the T4 generator which is part of Visual Studio.
I'm looking for something similar for Java, in particular an Eclipse add-in since I do all my Java development using the Eclipse IDE.
I've found that freemarker does a pretty good job for generating any type of code. From the website:
FreeMarker is a "template engine"; a generic tool to generate text output (anything from HTML to autogenerated source code) based on templates. It's a Java package, a class library for Java programmers. It's not an application for end-users in itself, but something that programmers can embed into their products.
It is used by struts2 a lot. The website has a long list of other products that use freemarker.
I have worked with both Velocity and StringTemplate. Velocity is a bit more conventional (think JSP/ASP concepts), while StringTemplate seems a bit cleaner. in a sense described in this Artima interview. Both are pure templating engines, and will require you to write some code around them, if you want to do full-blown code generation from a model.
StringTemplate is used internally by ANTLR, which may be useful to your effort.
As an alternative approach, you could go with Eclipse, using EMF and JET.
You should try Telosys Tools, an Eclipse plugin for code generation working from an existing database with customizable Velocity templates
See: http://www.telosys.org/
Eclipse Marketplace : http://marketplace.eclipse.org/content/telosys-tools
The tutorials are here : https://sites.google.com/site/telosystutorial/
See this other question about CodeSmith : Is there any freeware tool available which is like Codesmith?
I use JavaForger to generate code from templates. It parses existing classes so that you can use that class-data inside your templates. It can both create new classes or insert code into existing classes. You can determine where generated code will be inserted based on a string conversion rule (e.g. myProject/dao/ProductDao.java => myProject/service/ProductService.java).
JavaForger is open source and uses FreeMarker as template engine and JavaParser as parser.
This is an old question but the only thing that comes close (for Java) to do what CodeSmith Generator does is Spring Roo.
The reason is that Java does not have Partial Classes like C# does. Spring Roo gets around this by using AspectJ ITDs.
My answer is to use StringTemplate, but there is a bit more to it than just what tool to use.
Is it the issue to generate java code? Or is it to use java tools? Programmers would be normally very comfortable writing code. Therefore, it would not be a leap to write some java classes and write a walk that would generate code using StringTemplate. I personally think it is a good exercise to create example models, generate your java code from the models. And depending on your use case you could end up writing JSON models by hand and never having to write any java code to produce the java code. Or you could end up writing Java classes that produce equivalent models.
You could use the StringTemplate based STST, which reads JSON. STST is command line based, and I am sure you could hook it to both eclipse and/or Visual Studio.
I personally think about portability, JSON is an extremely simple language. And almost every language has libraries that support it.
I'm not a C# man so I don't know what the equivalents would be, however I've found xdoclet to be very good in the past. I don't think it integrates with eclipse as such but you can run it from an ant script. Does things like generating Hibernate mapping files from annotated Java classes. Useful if that's what you're looking for :)
eclipse has a built-in template system.
look in window -> preferences -> java -> code style -> code templates
You might look at my plugin : http://fast-code.sourceforge.net/. It allows one to select multiple fields and generate code using user specified velocity templates.
Take a look at my project https://github.com/karajdaar/templator and see if that helps.
I wrote a simple web based application for my use.
its available at https://github.com/harish2704/templates
and a demo is available at http://templates-harish2704.rhcloud.com/
Its language independent tool. GUI supports several languages ( highlighting, snippet completion ect )