Skip to Main Content

Calling Java Method from Objective C

PavlovOnlineJun 14 2015 — edited Jun 17 2015

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);
}

Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked due to inactivity on Jul 15 2015
Added on Jun 14 2015
1 comment
1,229 views