Java code generation - java

I am looking for nice (java) code generation engine.
I have found cglib but it is very poorly documented and I am not quite sure that it can generate actual java classes (files) and only dynamic classes. If I am wrong maybe someone knows has a link with an example.
Roman

Have a look at codemodel, used with success for my projects.

Didn't really try, but you may want to take a look at another code generation Java framework called Javassist, which also has pretty thorough tutorial. Also Hibernate changed code generation framework from cglib to javassist. Quote, explaining why:
The simple fact of the matter is that development on CGLIB has largely stopped. It happens. Developers for whatever reason (the reasons are their own) move on to new priorities.
Source

I just released cgV19 here: https://github.com/carstenSpraener/cgV19 it's based on a code generator i wrote in 2002 to 2006 and which is still in production use. cgV19 is a re implementation with lessons learned. It has:
Support for gradle
Uses Groovy as a template language
a modular "cartridge" system to add several generator for different aspects
small footprint
Just try it out and give me feedback would be very nice.

Related

How to refactor thousands of lines of Java code? Is there any tool available?

In our application we have two or three classes which contains the entire Java Swing application logic. These two or three classes contain around 7k lines of code.
Now I have been assigned the task to refactor this Java code.
How do I start? Is there any tool available that will do the refactoring or at least guide us?
I'd recommend Eclipse - the brilliant Java IDE for the editing and refactoring. It has several tools for refactoring. An excellent tutorial on how to do it with Eclipse is located at:
http://www.cs.umanitoba.ca/~eclipse/13-Refactoring.pdf
There's a brililant article on the power of refactoring with Eclipse, if you're not yet convinced, at:
http://www.eclipse.org/articles/article.php?file=Article-Unleashing-the-Power-of-Refactoring/index.html
And finally another article on how to refactor in Eclipse, including techniques and tools, is available at:
http://www.ibm.com/developerworks/opensource/library/os-ecref/
There's also another stackoverflow question on strategies for refactoring Java code that you may be interested in:
https://stackoverflow.com/questions/128498/what-are-the-best-code-refactoring-strategies
Hope that helps, good luck!
I assume that you are trying to break up these large classes into smaller ones. The most common way to do this is with the Extract Class refactoring. It just happens that this is a major topic in my PhD thesis work.
One of the hard parts is deciding what goes into the new classes. There are two publicly available tools that I know of that help - ExtC (my tool) and JDeodorant. Both are Eclipse plug-ins, and I would classify both as being prototypes. If you want to try to use my tool, I'll be glad to help.
Once you decide what should go into the new class, you have to do the actual work of separating the class into others. Eclipse's Extract Class refactoring is misnamed and isn't really helpful. IntelliJ's IDEA is much better, but still has some bugs. JDeodorant can also perform the split, but it also has some bugs.
IntelliJ has all the smarts for understanding Java code and provides excellent refactorings. And now there is a free and open source version.
Eclipse has some built-in refactoring tools. You could refactor method's signatures, extract interfaces and classes, pull methods up and down in the hierarchy tree, move packages ... and all that just by two clicks.
Also, you could start with a Martin Fowler book "Refactoring: Improving the Design of Existing Code".
As refactoring code relies primarily on the developer (assisted by tooling), your IDE is a very important tool when it comes to refactoring.
Both Eclipse and IntelliJ IDEA have plenty of refactoring support.
For an overview, checkout:
http://www.jetbrains.com/idea/features/refactoring.html
http://help.eclipse.org/galileo/index.jsp?topic=/org.eclipse.jdt.doc.user/concepts/concept-refactoring.htm
I have created my own refactoring tool that tries and group together methods that use the same set of variables. It is very much an early prototype. It is only available as a Windows Eclipse plugin.
Variable Usage Eclipse Plugin

Are there alternatives to cglib? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 8 years ago.
Improve this question
Just out of curiosity, are there any (stable) open source projects for runtime java code generation other than cglib? And why should I use them?
ASM java-asm
CGLIB and almost all other libraries are built on top of ASM which itself acts on a very low level. This is a show-stopper for most people as you have to understand the byte code and a little bit of the JVMS to use it properly. But mastering ASM is most certainly very interesting. Note however that while there is a great ASM 4 guide, in some part of the API the javadoc documentation can be very concise if it is present at all, but it is being improved. It closely follows JVM versions to support new features.
However, if you need full control, ASM is your weapon of choice.
This project sees regular updates ; at the time of this edit version 5.0.4 was released on May 15th 2015.
Byte Buddy byte-buddy
Byte Buddy is a rather new library but provides any functionality that CGLIB or Javassist provides and much more. Byte Buddy can be fully customised down to the byte code level and comes with an expressive domain specific language that allows for very readable code.
It supports all JVM bytecode versions, including Java 8 semantic changes of some opcodes regarding default methods.
ByteBuddy don't seem to suffer from the drawbacks other libraries have
Highly configurable
Quite fast (benchmark code)
Type safe fluent API
Type safe callbacks
Javassist advices or custom instrumentation code is based on code in a plain String thus type check and debugging is impossible within this code, while ByteBuddy allows to write those with pure Java hence enforces type checks and allows debugging.
Annotation driven (flexible)
The user callbacks can be configured with annotations allowing to receive the wanted parameters in the callback.
Available as an agent
The nifty agent builder allows ByteBuddy to be used as a pure agent or as attaching agent. It allows different kind
Very well documented
Lots of example
Clean code, ~94% test coverage
Android DEX support
The main downside perhaps, would the API is a bit verbose for a beginner but it is designed as an opt-in API shaped as a proxy generation DSL ; there's no magic or questionable defaults. When manipulating byte code it is probably the most safe and the most reasonable choice. Also with multiple examples and a big tutorial this is not a real issue.
In October 2015 this projects received the Oracle Duke's choice award. At this times it just reached the 1.0.0 milestone, which is quite an achievement.
Note that mockito has replaced CGLIB by Byte Buddy in version 2.1.0.
Javassist javassist
The javadoc of Javassist is way better than that of CGLIB. The class engineering API is OK, but Javassist is not perfect either. In particular, the ProxyFactory which is the equivalent of the CGLIB's Enhancer suffer from some drawbacks too, just to list a few :
Bridge method are not fully supported (ie the one that are generated for covariant return types)
ClassloaderProvider is a static field instead, then it applies to all instances within the same classloader
Custom naming could have been welcome (with checks for signed jars)
There is no extension point and almost all methods of interest are private, which is cumbersome if we want to change some behavior
While Javassist offer support for annotation attributes in classes, they are not supported in ProxyFactory.
On the aspect oriented side, one can inject code in a proxy, but this approach in Javassist is limited and a bit error-prone :
aspect code is written in a plain Java String that is compiled in opcodes
no type check
no generics
no lambda
no auto-(un)boxing
Also Javassist is recognized to be slower than Cglib. This is mainly due to its approach of reading class files instead of reading loaded classes such as CGLIB does. And the implementation itself is hard to read to be fair ; if one requires to make changes in the Javassist code there's many chances to break something.
Javassist suffered from inactivity as well, their move to github circa 2013 seem to have proven useful as it shows regular commits and pull requests from the community.
These limitations still stand in the version 3.17.1. Version has been bumped to version 3.20.0, yet it seems Javassist may still have issues with Java 8 support.
JiteScript
JiteScript does seem like a new piece of nicely shaping up DSL for ASM, this is based on the latest ASM release (4.0). The code looks clean.
But the project is still in his early age so API / behavior can change, plus the documentation is dire. And updates scarce if not abandoned.
Proxetta jodd
This is a rather new tool but it offers the by far best human API. It allows for different types of proxies such as subclass proxies (cglib approach) or weaving or delegation.
Although, this one is rather rare, no information exists if it works well. There are so many corner case to deal with when dealing with bytecode.
AspectJ aspectj
AspectJ is a very powerful tool for aspect-oriented programming (only). AspectJ manipulates byte code to achieve its goals such that you might be able to achieve your goals with it. However, this requires manipulation at compile-time; spring offer weaving at load time via an agent since version 2.5, 4.1.x.
CGLIB cglib
A word about CGLIB that has been updated since that question has been asked.
CGLIB is quite fast, it is one of the main reason why it is still around, along with the fact that CGLIB worked almost better than any alternatives until now (2014-2015).
Generally speaking libraries that allow the rewriting of classes at run time have to avoid loading any types before the corresponding class is rewritten. Therefore, they cannot make use of the Java reflection API which requires that any type used in reflection is loaded. Instead, they have to read the class files via IO (which is a performance-breaker). This makes for example Javassist or Proxetta significantly slower than Cglib which simply reads the methods via the reflection API and overrides them.
However, CGLIB is no longer under active development. There were recent releases but those changes were seen as insignificant by many and most people did never update to version 3 since CGLIB introduced some severe bugs in the last releases what did not really build up confidence. Version 3.1 fixed a lot of the woes of version 3.0 (since version 4.0.3 Spring framework repackages version 3.1).
Also, the CGLIB source code is of rather poor quality such that we do not see new developers joining the CGLIB project. For an impression of CGLIB's activeness, see their mailing list.
Note that following a proposition on the guice mailing list, CGLIB is now available on github to enable the community to better help the project, it appears to be working (multiple commits and pull requests, ci, updated maven), yet most concerns still remain.
At this time there are working on version 3.2.0, and they are focusing effort on Java 8, but so far users that want that java 8 support have to use tricks at build time. But progress is very slow.
And CGLIB is still known to be plagued for PermGen memory leak. But other projects may not have been battle tested for so many years.
Compile time annotation Processing annotation-processing
This one is not runtime of course, but is an important part of the ecosystem, and most code generation usage don't need runtime creation.
This started with Java 5 that came with the separate command line tool to process annotations : apt, and starting from Java 6 annotation processing is integrated into the Java compiler.
At some time you were required to explicitly pass the processor, now with the ServiceLoader approach (just add this file META-INF/services/javax.annotation.processing.Processor to the jar) the compiler can detect automatically the annotation processor.
This approach at code generation has drawbacks too it require a lot of work and understanding of the Java language not bytecode. This API is a bit cumbersome, and as one is plugin in the compiler one must take extreme care to make this code the most resilient and user friendly error message.
The biggest advantage here is that it avoids another dependency at runtime, you may avoid permgen memory leak. And one has full control on the generated code.
Conclusion
In 2002 CGLIB defined a new standard to manipulate bytecode with ease. Many tools and methodology (CI, coverage, TDD, etc.) we have nowadays were not available or not mature at that time. CGLIB managed to be relevant for more than a decade ; that's a pretty decent achievement. It was fast and with an easy API to use than manipulating opcodes directly.
It defined new standard regarding code generation but nowadays it isn't anymore because environment and requirements have changed, so have the standards and goals.
The JVM changed and will change in recent and future Java (7/8/9/10) versions (invokedynamic, default methods, value types, etc). ASM upgraded his API and internals regularly to follow these changes but CGLIB and others have yet to use them.
While annotation processing is getting traction, it is not as flexible as runtime generation.
As of 2015, Byte Buddy — while rather new on the scene — offer the most compelling selling points for runtime generation. A decent update rate, and the author has an intimate knowledge of the Java byte code internals.
Javassist.
If you need to make proxies, take a look at commons-proxy - it uses both CGLIB and Javassit.
I prefer raw ASM, which I believe is used by cglib anyway. It's low level, but the documentation is brilliant, and once you get used to it you'll be flying.
To answer your second question, you should use code generation when your reflection and dynamic proxies are beginning to feel a bit cobbled together and you need a rock solid solution. In the past I've even added a code generation step into the build process in Eclipse, effectively giving me compile time reporting of anything and everything.
I think it's more sense to use Javassist instead of cglib. E.g. javasist perfectly works with signed jars unlike cglib. Besides, such grand as Hibernate project decided to stop using cglib in favor of Javassist.
CGLIB was designed and implemented more than ten years ago in AOP and ORM era.
Currently I see no reasons to use it and I do not maintain this library anymore (except bug fixes for my legacy applications ).
Actually all of CGLIB use cases I have ever saw are anti patterns in modern programming.
It should be trivial to implement the same functionality via any JVM scripting language e.g. groovy.

other than framework and java syntax, what else is a must to master?

Other than learning java, spring, hibernate, servlets, jsp's, how to use eclipse/netbeans, databases like mysql/oracle/postgresql, JMS, JUnit, etc.
What other skills are essential?
Coming from a MS background, and I am just a little overwhelmed by all the things going on in the java world! (btw, you guys have TONS of dlls also, a big eye-opener for me in my java pursuits)
Other things I can come up with so far are solid linux skills, maybe how to use a mac.
Other than that, there are so many of these tools that I see referenced, which so far I am pretty much clueless how to use:
ant
maven
what else is there that are common or important to know?
Debugging techniques
XML technologies (SAX, DOM, XPath)
How to find libraries that do what you're attempting to accomplish, rather than writing them yourself.
The number #1 tip for you:
How to research.
Debugging techniques
How to learn a new API/framework
Java concurrency API
The standard tools (JConsole, jmap, VisualVM, etc.)
Profiling techniques
GC tunning
The Java memory model.
As well written/well thought Java code to read and learn from I would suggest Google-collections (or Guava) and maybe Functional Java and Guice.
It depends. When you are experienced with the foundations (automated testing, design, know how to 'learn' generally, modeling, working well with other programmers, etc.) you are lucky :) Technologies change often but you can adapt extremely quickly if you have the much less changing concepts in your head and fingers.
Still the frameworks + techs are different. So get used to new tools (Java has different tool-set and IDEs as MS-tools), this also includes build-envs like maven or ant. For getting used with new tools find a little private project (with small scope). And then step by step puzzle together + solve your technology todo-list.
Parallel to that download a little open-source project based on Java and see how they did the stuff. And read a lot of code done by others!
how about documentation - javadoc

Which is the simplest and least dependent AOP framework in Java?

I want to use an AOP framework, but I have two constraints.
Any framework that I choose
Must be fairly independent. I plan to use this in a legacy code base, and hence
cannot upgrade prospective dependencies like commons-logging-XXX.jar to commons-logging-newest.jar.
Must be fairly well documented, should not be too complex to understand and integrate.
AspectJ as far as I can tell is just a compiler and imposes no dependencies on compiled programs other than including the AspectJ runtime jar.
It is also actively maintained, part of the Eclipse project and has a nice development environment (AJDT, a plugin to Eclipse).
I like Spring + AspectJ. You can do all of your pointcut definitions in xml if you like, and you don't need to change a line of code on your legacy stuff. If you already know spring and AOP concepts, there's not much to learn.
Okay, this one doesn't fit all your requirements, but I think, it's worth a look:
http://dynamicaspects.sourceforge.net/
Positives
No dependencies except needs java 1.5 due to using the JavaAgent
No XML markup needed and just works with POJO classes
Tried myself and found it very easy to use (not very complex)
Negatives
No more activly maintained afaik
Poor documentation
You cannot do everything a full fledged AOP framework allows you to do
I tested it out some time ago and was pretty impressed but found some glitches which I don't remember right now. Though you might give it a try.
Greetz, GHad

Is there an effective tool to convert C# code to Java code? [duplicate]

This question already has answers here:
Where can I find a Java to C# converter? [closed]
(9 answers)
Closed 7 years ago.
Is there an effective tool to convert C# code to Java code?
I have never encountered a C#->Java conversion tool. The syntax would be easy enough, but the frameworks are dramatically different. Even if there were a tool, I would strongly advise against it. I have worked on several "migration" projects, and can't say emphatically enough that while conversion seems like a good choice, conversion projects always always always turn in to money pits. It's not a shortcut, what you end up with is code that is not readable, and doesn't take advantage of the target language. speaking from personal experience, assume that a rewrite is the cheaper option.
We have an application that we need to maintain in both C# and Java. Since we actively maintain this product, a one-time port wasn't an option. We investigated Net2Java and the Mainsoft tools, but neither met our requirements (Net2Java for lack of robustness and Mainsoft for cost and lack of source code conversion). We created our own tool called CS2J that runs as part of our nightly build script and does a very effective port of our C# code to Java. Right now it is precisely good enough to translate our application, but would have a long way to go before being considered a comprehensive tool. We've licensed the technology to a few parties with similar needs and we're toying with the idea of releasing it publicly, but our core business just keeps us too busy these days.
This blog post suggests useful results from Tangible.
There is a tool from Microsoft to convert java to C#. For the opposite direction take a look here and here. If this doesn't work out, it should not take too long to convert the source manually because C# and java are very similar,
These guys seem to have a solution for this, but I haven't tried yet. They also have a demo version of the converter.
Although this is an old-ish question, take a look at xmlVM http://www.xmlvm.org/clr2jvm, I'm not sure if it's mature enough yet, although it has been around for several years now. XMLvm was made, I believe, primarily for translating Android Java apps to the iPhone, however, its XML-code-translation-based framework is flexible enough to do other combinations (see the diagrams on the site).
As for a reason to do this conversion, maybe there is a need to 'hijack' some of the highly abundant oss code out there and use it within his/their own [Java] project.
Cheers
Rich
Try to look at Net2Java It seems to me the best option for automatic (or semi-automatic at least) conversion from C# to Java
They don't convert directly, but it allows for interoperability between .NET and J2EE.
http://www.mainsoft.com/products/index.aspx
C# has a few more features than Java. Take delegates for example: Many very simple C# applications use delegates, while the Java folks figures that the observer pattern was sufficient. So, in order for a tool to convert a C# application which uses delegates it would have to translate the structure from using delegates to an implementation of the observer pattern.
Another problem is the fact that C# methods are not virtual by default while Java methods are. Additionally, Java doesn't have a way to make methods non virtual. This creates another problem: an application in C# could leverage non virtual method behavior through polymorphism in a way the does not translate directly to Java.
If you look around you will probably find that there are lots of tools to convert Java to C# since it is a simpler language (please don't flame me I didn't say worse I said simpler); however, you will find very few if any decent tools that convert C# to Java.
I would recommend changing your approach to converting from Java to C# as it will create fewer headaches in the long run. Db4Objects recently released their internal tool which they use to convert Db4o into C# to the public. It is called Sharpen. If you register with their site you can view this link with instructions on how to use Sharpen:
http://developer.db4o.com/Resources/view.aspx/Reference/Sharpen/How_To_Setup_Sharpen
(I've been registered with them for a while and they're good about not spamming)
I'm not sure what you are trying to do by wishing to convert C# to java, but if it is .net interoperability that you need, you might want to check out Mono
This is off the cuff, but isn't that what Grasshopper was for?
Well the syntax is almost the same but they rely on different frameworks so the only way to convert is by getting someone who knows both languages and convert the code :) the answer to your question is no there is no "effective" tool to convert c# to java
Possibly you could use jni4net - opensource bridge instead ?
Or list of other options I know.
Why not write it in Haxe (http://haxe.org/) and convert it to whatever you want it to be?

Categories