Calling methods on a java object parameter
Hi Gurus:
I need to know how I can call methods (inside native code) on a Java object that I passed into the native method.
This might be helpful in understanding what I want:
JNIEXPORT jobjectArray JNICALL Java_translate_CgmTranslation_createCGM
(JNIEnv *env, jobject thisobject, jobject part)
{
// This is what I want to do
cout << "Part Number = " << part.getNumber() << endl;
.
.
.
}
where part is a java object (Part) derived from the default java class, which has a method called getNumber() returning a String.
Regards,
Kamran
[664 byte] By [
kamranA] at [2007-9-26 23:49:12]

You use JNI to do it. Since you have an object reference, you use a JNI routine to look up the method, and another to actually execute the method.
Warning: I doubt that you will be able to use the results directly in a C++ output stream. You will probably have to do some type conversion (for which there are also JNI methods.
I suggest that you start by looking at the documentation for GetMethodId, Call<type>Method. You should also review the information about the correspondence between native types and java types.
kamranA wrote:
cout << "Part Number = " << part.getNumber() << endl;
This is exactly what Jace, http://jace.reyelts.com/jace, helps you do. Your code would look exactly like this:JNIEXPORT jobjectArray JNICALL Java_translate_CgmTranslation_createCGM
( JNIEnv *env, jobject thisobject, jobject jPart ) {
Part part( jPart );
cout << "Part Number = " << part.getNumber() << endl;
}
The roughly equivalent bare-bones JNI would be:JNIEXPORT jobjectArray JNICALL Java_translate_CgmTranslation_createCGM
( JNIEnv *env, jobject thisobject, jobject jPart ) {
jclass partClass = env->GetObjectClass( jPart );
jmethodID partNumberMethod = env->GetMethodID( partClass, "getNumber", "()Ljava/lang/String;" );
if ( ! methodID ) {
cout << "Unable to locate the method ID for Part.getNumber()" << endl;
return;
}
jstring jPartNumberStr = static_cast<jstring>( env->CallObjectMethod( jPart, partNumberMethod ) );
if ( env->ExceptionOccurred() ) {
cout << "An exception occurred while calling Part.getNumber()" << endl;
return;
}
const char* partNumberStr = env->GetStringUTFChars( jPartNumberStr, NULL );
if ( ! partNumberStr ) {
cout << "A JNI failure occurred while trying to retrieve the contents of the part number string." << endl;
return;
}
cout << "Part Number = " << partNumberStr << endl;
env->ReleaseStringUTFChars( jPartNumberStr, partNumberStr );
}
See any differences?
God bless,
-Toby Reyelts
Thanks rreyelts for your response.
And bschauwe:
> I suggest that you start by looking at the
> documentation for GetMethodId, Call<type>Method. You
> should also review the information about the
> correspondence between native types and java types.
Where do I find documentation for jni? I have searched all over the sun website, didn't find it.
Kamran