Java Reference
In-Depth Information
Both of these commands should produce the following output:
main: calling nativeHelloWorldStatic()
<native> Hello World (static)
main: instantiating JNIHelloWorld
ctor: calling nativeHelloWorld()
<native> Hello World (non-static)
main: exiting
If you try this example and do not see the output shown above, then you've
made some mistake. The most common runtime error when running a simple
example like this is an
UnsatisfiedLinkError
,which can occur because of
two situations. If an error message like this
Exception in thread
"
main
"
java.lang.UnsatisfiedLinkError:
no NativeHelloWorld in java.library.path
appears, then the system could not find the shared library file, almost surely
because of an incorrect
PATH
or
java.library.path
setting. The stack trace
should lead to the Java source code line that calls
System.loadLibrary()
.
The other possible reason for an
UnsatisfiedLinkError
is that the spec-
ified library was found but a required native method could not be found in that
library. This problem can sometimes happen if one has declared many native
methods and simply forgotten to implement one of them. Perhaps more likely,
the native method signature is not quite letter perfect. In both cases, the error
message simply includes the name of the native method that cannot be found.
An example would be mistakenly using
jclass
instead of
jobject
when
implementing the
nativeHelloWorld
method. Recall that
jclass
is used
for static implementations but that
jobject
is required for non-static methods
like
nativeHelloWorld
. Since there is no (correct) implementation of the
required non-static
nativeHelloWorld
method, the JVM is unable to locate
that method when needed and the error message reads
Exception in thread
"
main
"
java.lang.UnsatisfiedLinkError:
nativeHelloWorld
The stack trace should lead to where the Java source first attempted to call
nativeHelloWorld
.Ifyou're sure the native method being called is present,
be sure to check that the signature in your implementation exactly matches the
signature in the generated header file.
22.4 Deeper into JNI
The example above served as a useful introduction to JNI but omitted many
features. It did not pass any parameters from the Java side to the C side, did
not return a value back to Java, did not use the important
JNIEnv
pointer, and
Search WWH ::
Custom Search