Search code examples
javaobjective-ccocoajava-native-interface

Calling Java Method from Objective C


I am trying to invoke a simple helloWorld java method from Objective C via JNI.

The JNI starts, but FindClass returns nil. No class is found, therefore, can't invoke the method.

Please suggest.

My setup:

Java class (located on desktop, compiled with javac)

public class HelloWorld {
    public static void main(String[] args) { 
         System.out.println("Hello, World");
    }
}

Objective C

JNIEnv* jniEnv;
JavaVM* javaVM;

- (void)launch {
    JavaVMOption javaVMOptions[2];
    javaVMOptions[0].optionString = "-Djava.awt.headless=true";

    // directory path
    javaVMOptions[1].optionString = "-Djava.class.path=/Users/me/Desktop";

    JavaVMInitArgs javaVMInitArgs;
    javaVMInitArgs.version = JNI_VERSION_1_6;
    javaVMInitArgs.options = javaVMOptions;
    javaVMInitArgs.nOptions = 1;
    javaVMInitArgs.ignoreUnrecognized  = JNI_TRUE;

    int result = JNI_CreateJavaVM(&javaVM, (void**)&jniEnv, &javaVMInitArgs);
    NSLog(@"Java vm launched %i", result);
    invoke_class(jniEnv);
}


void invoke_class(JNIEnv* env) {
    jclass helloWorldClass;
    jmethodID mainMethod;
    jobjectArray applicationArgs;
    jstring applicationArg0;

    helloWorldClass = (*env)->FindClass(env, "HelloWorld");

    mainMethod = (*env)->GetStaticMethodID(env, helloWorldClass, "main", "([Ljava/lang/String;)V");

    applicationArgs = (*env)->NewObjectArray(env, 1, (*env)->FindClass(env, "java/lang/String"), NULL);
    applicationArg0 = (*env)->NewStringUTF(env, "From-C-program");
    (*env)->SetObjectArrayElement(env, applicationArgs, 0, applicationArg0);

    (*env)->CallStaticVoidMethod(env, helloWorldClass, mainMethod, applicationArgs);
}

Solution

  • You have javaVMInitArgs.nOptions = 1; in your code so the VM only sees the first option and not the class path declaration.