j2objc

How to include "import" when using j2ojbc?


Hi I'm trying to convert a java project to objc. However there are still some hiccups when I'm trying to do so.

error: package com.zzz.yyy.xxx does not exist import com.zzz.yyy.xxx.Test;

e.g.:

error: package com.google.gson does not exist import com.google.gson.Gson;

error: package com.google.gson.stream does not exist import com.google.gson.stream.JsonReader;

We can use -classpath to cater for jar file. How do we cater for those packages?


Solution

  • Just like Java, the code your app references from other libraries needs to be available when the app executes, as does the code those libraries reference. For j2objc, that means that all libraries your code depends upon also have to be translated to Objective C and included in your iOS app. The -classpath should only hold jars which either have translations (such as those included in the j2objc distribution, like JUnit and Guava), or will have translations later.

    For an external library like Gson, you need to either download its source code, or a jar file with its source, and add that jar file or the root directory of the source to your -sourcepath. It still needs to be translated, though. Many developers find it easier to start with javac to build a -sourcepath argument without any dependencies on the class path, then change "javac" to "j2objc" and add any j2objc-specific flags (that's why the two compilers share many flags).

    If you are building on the command-line, j2objc's --build-closure flag will translate the sources you list, and then (like javac) compile all referenced sources it finds on the specified source path. This has the advantage of only compiling the actual code your app needs, instead of the whole library. Build tools like Xcode have trouble with this flag (and with javac's behavior), though, because the list of rule output files cannot be constructed from its input list.

    If all your app needs is to parse basic Json, you can instead use the org.json package built into j2objc's JRE emulation. It's the same code as on Android, so it's cross-platform. But many published apps use Gson on iOS, so that shouldn't be a blocker.