To facilitate your ability to see how this works in practice, my explanation I will use a Foundation tool. Note: I have verified that the same steps work for any Objective-C project type
Read the rest of the hint for the step-by-step explanation...
- Create a new Foundation project called "HelloBridge"
- Create a new Pure Java Package target called "JavaClasses"
- Create a new Java class called "HelloBridge.java" an add it to target "JavaClasses":
public class HelloBridge { private String string = "Hello"; public void setString(String string) { this.string = string; } public String getString() { return this.string; } public void printString() { System.out.println(this.string); } } - Add "HelloBridge.java" to the "Sources" build phase in target "JavaClasses"
- Create a new empty file called "JavaInterfaces.h" and add it to target "HelloBridge":
// Provide Objective-C interfaces for the Java classes // Not only good practice, it provides Code Sense @interface java_util_Vector : NSObject {} - (void)add:(id)anObject; - (id)get:(int)index; @end @interface HelloBridge : NSObject {} - (void)setString:(NSString *)string; - (NSString *)getString; - (void)printString; @end - Modify "main.m":
#import <Foundation/Foundation.h> #import "JavaInterfaces.h" int main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; // Load the Java VM id vm = NSJavaSetupVirtualMachine(); // Start the Java class loader NSJavaClassesFromPath(nil, nil, YES, &vm); // Load a new instance of the java.util.Vector Java class into an Objective-C pointer java_util_Vector * vector = NSJavaObjectNamedInPath(@"java.util.Vector", nil); [vector add:@"one item!"]; NSLog(@"item 1=%@",[vector get:0]); [vector release]; // Load a new instance of our custom HelloBridge Java class into an Objective-C pointer HelloBridge * hello = NSJavaObjectNamedInPath(@"HelloBridge", nil); NSLog(@"item 1=%@",[hello getString]); [hello setString:@"Test"]; NSLog(@"item 1=%@",[hello getString]); [hello printString]; [hello release]; [pool release]; return 0; } - Select "JavaClasses" from the targets drop box and Build it
- Select "HelloBridge" from the targets drop box and Build/Run it
- Gloat to all of your friends about how awesome OS X is for development

