- A Simple Example
- Java Class
- Java Header
- Setting up Java
- Objective-C Class
- Conclusion
Setting up Java
Just adding Java source code to the project is not enough to let the Cocoa application know how to use Java. A few extra steps are needed. First, the Java code needs a target of its own. Add a Java target to the project and specify a Java package template. I named this target JavaCompile (without a space). This target will create a jar file named JavaCompile.jar. Add the URLRetriever to this target.
Next, double-click on the default target to open its properties window. There is a list of direct dependencies in the general tab, which is just like the "depends" tag in an Ant build file. Adding the JavaCompile target to this list will ensure that the JavaCompile gets built prior to the default target.
To get the jar file included in the final application, it needs to be added to the bundle resources of the default target. Clicking the arrow next to the default target will show the list of steps that are part of this target. Drag the JavaCompile.jar file from the Products list to the Copy Bundle Resources step will ensure that the jar file is copied into the final app bundle.
The last thing that needs to be done is to alter the Info.plist file. Three keys need to be added to the Info.plist so that the JavaVM is loaded and the classpath is set properly.
<key>NSJavaNeeded</key> <string>YES</string>
This key tells Cocoa that this application uses Java, which will cause the JavaVM to be started up when the application starts up.
<key>NSJavaRoot</key> <string>Contents/Resources</string>
This key tells Cocoa to set the root path for the JavaVM to Contents/Resources inside of the application bundle. If the Java portion of the application needs to load any files, they would be placed relative to this location.
<key>NSJavaPath</key> <array> <string>JavaCompile.jar</string> </array>
This key sets the classpath for the JavaVM. All the items in this key are relative to the NSJavaRoot set above. In this example, only one jar file is included in the classpath. If this application were to use any third-party libraries, they would be included in this list.
With these changes, the application now knows that it is utilizing the Java Virtual Machine and will start it when the application starts.