How many times has this happened to you? You are coding up a native application for your favorite mobile OS. While all this coding is going on, you are thinking in the back of your head how all of this work is going to have to be re-done when you build the same application for your lesser favorite mobile OS as per business requirements.
This scenario makes a couple of assumptions. Mostly that your favorite mobile OS is Android and your lesser favorite mobile OS is iOS. That in mind, this exact scenario has happened to me a number of times. If only there were a way to write Java code and use that with Objective C as research has proven that, on average, developers can code in Java more quickly than in C languages. Thanks to Google, we now have a tool to help with reuse of this code.
The tool that Google created is J2ObjC. J2ObjC is an open-source command-line tool that translates Java code to Objective-C for iOS. J2ObjC enables Java to be part of an iOS application build. No editing of generated files is required. J2ObjC is meant to be used for all non-UI code such as data access and application/business logic. It also supports most Java language and runtime features including exceptions, inner and anonymous classes, generic types, threads and reflection. J2ObjC is currently in a state between alpha and beta. Google relies on using J2ObjC on a number of their mobile projects.
Using J2ObjC is fairly straightforward. Simply download the zip, extract, and you are ready to go.
For a simple example we can use a typical hello world java file:
Now simply open terminal and run the following command against that java file:
$ j2objc Hello.java
J2ObjC now creates the .h and .m files and that code can be used directly in your projects:
While J2OjbC is still technically Alpha, it does work very well and is mostly dependant on the style in which you code. It is constantly being updated and is used by Google on a number of projects. There are far too many other features it includes to include on this blog post so I encourage you to check out the projects homepage if you are at all interested. I can really see this saving a lot of time for Android and iOS projects that will share a lot of the same logic and I am excited to try it out on my next project.
If you have had a chance to try this tool out, what are your thoughts?