Movatterモバイル変換


[0]ホーム

URL:


Java SE 24 & JDK 24

Java Native Interface Specification: 4 - JNIFunctions

This chapter serves as the reference section for the JNI functions.It provides a complete listing of all the JNI functions. It alsopresents the exact layout of the JNI function table.

Note the use of the term "must" to describe restrictions on JNIprogrammers. For example, when you see that a certain JNI functionmust receive a non-NULL object, it is your responsibility toensure that NULL is not passed to that JNI function. As a result, a JNIimplementation does not need to perform NULL pointer checks in that JNIfunction. Passing NULL when explicity not allowed may result in anunexpected exception or a fatal crash.

Functions whose definition may both returnNULL andthrow an exception on error, may choose only to returnNULLto indicate an error, but not throw any exception. For example, a JNIimplementation may consider an "out of memory" condition temporary, andmay not wish to throw anOutOfMemoryError since this wouldappear fatal (JDK APIjava.lang.Error documentation:"indicates serious problems that a reasonable application should nottry to catch").

A portion of this chapter is adapted from Netscape’s JRIdocumentation.

The reference material groups functions by their usage. The referencesection is organized by the following functional areas:


Interface Function Table

Each function is accessible at a fixed offset through theJNIEnv argument. TheJNIEnv type is a pointer to astructure storing all JNI function pointers. It is defined asfollows:

typedef const struct JNINativeInterface *JNIEnv;

The VM initializes the function table, as shown by the following codeexample. Note that the first three entries are reserved for futurecompatibility with COM. In addition, we reserve a number of additionalNULL entries near the beginning of the function table, sothat, for example, a future class-related JNI operation can be addedafter FindClass, rather than at the end of the table.

Note that the function table can be shared among all JNI interfacepointers.

const struct JNINativeInterface ... = {    NULL,    NULL,    NULL,    NULL,    GetVersion,    DefineClass,    FindClass,    FromReflectedMethod,    FromReflectedField,    ToReflectedMethod,    GetSuperclass,    IsAssignableFrom,    ToReflectedField,    Throw,    ThrowNew,    ExceptionOccurred,    ExceptionDescribe,    ExceptionClear,    FatalError,    PushLocalFrame,    PopLocalFrame,    NewGlobalRef,    DeleteGlobalRef,    DeleteLocalRef,    IsSameObject,    NewLocalRef,    EnsureLocalCapacity,    AllocObject,    NewObject,    NewObjectV,    NewObjectA,    GetObjectClass,    IsInstanceOf,    GetMethodID,    CallObjectMethod,    CallObjectMethodV,    CallObjectMethodA,    CallBooleanMethod,    CallBooleanMethodV,    CallBooleanMethodA,    CallByteMethod,    CallByteMethodV,    CallByteMethodA,    CallCharMethod,    CallCharMethodV,    CallCharMethodA,    CallShortMethod,    CallShortMethodV,    CallShortMethodA,    CallIntMethod,    CallIntMethodV,    CallIntMethodA,    CallLongMethod,    CallLongMethodV,    CallLongMethodA,    CallFloatMethod,    CallFloatMethodV,    CallFloatMethodA,    CallDoubleMethod,    CallDoubleMethodV,    CallDoubleMethodA,    CallVoidMethod,    CallVoidMethodV,    CallVoidMethodA,    CallNonvirtualObjectMethod,    CallNonvirtualObjectMethodV,    CallNonvirtualObjectMethodA,    CallNonvirtualBooleanMethod,    CallNonvirtualBooleanMethodV,    CallNonvirtualBooleanMethodA,    CallNonvirtualByteMethod,    CallNonvirtualByteMethodV,    CallNonvirtualByteMethodA,    CallNonvirtualCharMethod,    CallNonvirtualCharMethodV,    CallNonvirtualCharMethodA,    CallNonvirtualShortMethod,    CallNonvirtualShortMethodV,    CallNonvirtualShortMethodA,    CallNonvirtualIntMethod,    CallNonvirtualIntMethodV,    CallNonvirtualIntMethodA,    CallNonvirtualLongMethod,    CallNonvirtualLongMethodV,    CallNonvirtualLongMethodA,    CallNonvirtualFloatMethod,    CallNonvirtualFloatMethodV,    CallNonvirtualFloatMethodA,    CallNonvirtualDoubleMethod,    CallNonvirtualDoubleMethodV,    CallNonvirtualDoubleMethodA,    CallNonvirtualVoidMethod,    CallNonvirtualVoidMethodV,    CallNonvirtualVoidMethodA,    GetFieldID,    GetObjectField,    GetBooleanField,    GetByteField,    GetCharField,    GetShortField,    GetIntField,    GetLongField,    GetFloatField,    GetDoubleField,    SetObjectField,    SetBooleanField,    SetByteField,    SetCharField,    SetShortField,    SetIntField,    SetLongField,    SetFloatField,    SetDoubleField,    GetStaticMethodID,    CallStaticObjectMethod,    CallStaticObjectMethodV,    CallStaticObjectMethodA,    CallStaticBooleanMethod,    CallStaticBooleanMethodV,    CallStaticBooleanMethodA,    CallStaticByteMethod,    CallStaticByteMethodV,    CallStaticByteMethodA,    CallStaticCharMethod,    CallStaticCharMethodV,    CallStaticCharMethodA,    CallStaticShortMethod,    CallStaticShortMethodV,    CallStaticShortMethodA,    CallStaticIntMethod,    CallStaticIntMethodV,    CallStaticIntMethodA,    CallStaticLongMethod,    CallStaticLongMethodV,    CallStaticLongMethodA,    CallStaticFloatMethod,    CallStaticFloatMethodV,    CallStaticFloatMethodA,    CallStaticDoubleMethod,    CallStaticDoubleMethodV,    CallStaticDoubleMethodA,    CallStaticVoidMethod,    CallStaticVoidMethodV,    CallStaticVoidMethodA,    GetStaticFieldID,    GetStaticObjectField,    GetStaticBooleanField,    GetStaticByteField,    GetStaticCharField,    GetStaticShortField,    GetStaticIntField,    GetStaticLongField,    GetStaticFloatField,    GetStaticDoubleField,    SetStaticObjectField,    SetStaticBooleanField,    SetStaticByteField,    SetStaticCharField,    SetStaticShortField,    SetStaticIntField,    SetStaticLongField,    SetStaticFloatField,    SetStaticDoubleField,    NewString,    GetStringLength,    GetStringChars,    ReleaseStringChars,    NewStringUTF,    GetStringUTFLength,    GetStringUTFChars,    ReleaseStringUTFChars,    GetArrayLength,    NewObjectArray,    GetObjectArrayElement,    SetObjectArrayElement,    NewBooleanArray,    NewByteArray,    NewCharArray,    NewShortArray,    NewIntArray,    NewLongArray,    NewFloatArray,    NewDoubleArray,    GetBooleanArrayElements,    GetByteArrayElements,    GetCharArrayElements,    GetShortArrayElements,    GetIntArrayElements,    GetLongArrayElements,    GetFloatArrayElements,    GetDoubleArrayElements,    ReleaseBooleanArrayElements,    ReleaseByteArrayElements,    ReleaseCharArrayElements,    ReleaseShortArrayElements,    ReleaseIntArrayElements,    ReleaseLongArrayElements,    ReleaseFloatArrayElements,    ReleaseDoubleArrayElements,    GetBooleanArrayRegion,    GetByteArrayRegion,    GetCharArrayRegion,    GetShortArrayRegion,    GetIntArrayRegion,    GetLongArrayRegion,    GetFloatArrayRegion,    GetDoubleArrayRegion,    SetBooleanArrayRegion,    SetByteArrayRegion,    SetCharArrayRegion,    SetShortArrayRegion,    SetIntArrayRegion,    SetLongArrayRegion,    SetFloatArrayRegion,    SetDoubleArrayRegion,    RegisterNatives,    UnregisterNatives,    MonitorEnter,    MonitorExit,    GetJavaVM,    GetStringRegion,    GetStringUTFRegion,    GetPrimitiveArrayCritical,    ReleasePrimitiveArrayCritical,    GetStringCritical,    ReleaseStringCritical,    NewWeakGlobalRef,    DeleteWeakGlobalRef,    ExceptionCheck,    NewDirectByteBuffer,    GetDirectBufferAddress,    GetDirectBufferCapacity,    GetObjectRefType,    GetModule,    IsVirtualThread,    GetStringUTFLengthAsLong  };

Constants

There are a number of general constants used throughout the JNIAPI.

Boolean values

#define JNI_FALSE 0#define JNI_TRUE 1

Return codes

General return value constants for JNI functions.

#define JNI_OK           0                 /* success */#define JNI_ERR          (-1)              /* unknown error */#define JNI_EDETACHED    (-2)              /* thread detached from the VM */#define JNI_EVERSION     (-3)              /* JNI version error */#define JNI_ENOMEM       (-4)              /* not enough memory */#define JNI_EEXIST       (-5)              /* VM already created */#define JNI_EINVAL       (-6)              /* invalid arguments */

Version Information


GetVersion

jint GetVersion(JNIEnv *env);

Returns the version of the native method interface. For Java SEPlatform 24 and later, it returnsJNI_VERSION_24. Thefollowing table gives the version of JNI included in each release of theJava SE Platform (for older versions of JNI, the JDK release is usedinstead of the Java SE Platform):

Java SE PlatformJNI Version
1.1JNI_VERSION_1_1
1.2JNI_VERSION_1_2
1.3JNI_VERSION_1_2
1.4JNI_VERSION_1_4
5.0JNI_VERSION_1_4
6JNI_VERSION_1_6
7JNI_VERSION_1_6
8JNI_VERSION_1_8
9JNI_VERSION_9
10JNI_VERSION_10
11JNI_VERSION_10
12JNI_VERSION_10
13JNI_VERSION_10
14JNI_VERSION_10
15JNI_VERSION_10
16JNI_VERSION_10
17JNI_VERSION_10
18JNI_VERSION_10
19JNI_VERSION_19
20JNI_VERSION_20
21JNI_VERSION_21
22JNI_VERSION_21
23JNI_VERSION_21
24JNI_VERSION_24

LINKAGE:

Index 4 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

RETURNS:

Returns the major version number in the higher 16 bits and the minorversion number in the lower 16 bits.


Version Constants

#define JNI_VERSION_1_1 0x00010001#define JNI_VERSION_1_2 0x00010002#define JNI_VERSION_1_4 0x00010004#define JNI_VERSION_1_6 0x00010006#define JNI_VERSION_1_8 0x00010008#define JNI_VERSION_9   0x00090000#define JNI_VERSION_10  0x000a0000#define JNI_VERSION_19  0x00130000#define JNI_VERSION_20  0x00140000#define JNI_VERSION_21  0x00150000#define JNI_VERSION_24  0x00180000

Class Operations


DefineClass

jclass DefineClass(JNIEnv *env, const char *name, jobject loader, const jbyte *buf, jsize bufLen);

Loads a class from a buffer of raw class data. The buffer containingthe raw class data is not referenced by the VM after the DefineClasscall returns, and it may be discarded if desired.

LINKAGE:

Index 5 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

name: the name of the class or interface to be defined.The string is encoded in modified UTF-8. This value may beNULL, or it must match the name encoded within the classfile data.

loader: a class loader assigned to the defined class.This value may beNULL, indicating the"null classloader" (or"bootstrap class loader").

buf: buffer containing the.class filedata. ANULL value will cause aClassFormatError.

bufLen: buffer length.

RETURNS:

Returns a Java class object orNULL if an erroroccurs.

THROWS:

ClassFormatError: if the class data does not specify avalid class.

ClassCircularityError: if a class or interface would beits own superclass or superinterface.

OutOfMemoryError: if the system runs out of memory.

SecurityException: if the caller attempts to define aclass in the "java" package tree.


FindClass

jclass FindClass(JNIEnv *env, const char *name);

In JDK release 1.1, this function loads a locally-defined class. Itsearches the directories and zip files specified by theCLASSPATH environment variable for the class with thespecified name.

Since JDK 1.2,FindClass locates the class loaderassociated with the current native method; that is, the class loader ofthe class that declared the native method. If the native method belongsto a system class, no class loader will be involved. Otherwise, theproper class loader will be invoked to load, link, and initialize, thenamed class.

Since JDK 1.2, whenFindClass is called through theInvocation Interface, there is no current native method or itsassociated class loader. In that case, the result ofClassLoader.getSystemClassLoader is used. This is the classloader the virtual machine creates for applications, and is able tolocate classes listed in thejava.class.path property.

IfFindClass is called from a library lifecycle functionhook, the class loader is determined as follows:

Thename argument is a fully-qualified class name or anarray type signature. For example, the fully-qualified class name forthejava.lang.String class is:

    "java/lang/String"

The array type signature of the array classjava.lang.Object[] is:

    "[Ljava/lang/Object;"

LINKAGE:

Index 6 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

name: a fully-qualified class name (that is, a packagename, delimited by "/", followed by the class name). If thename begins with "[" (the array signature character), itreturns an array class. The string is encoded in modified UTF-8. ANULL value may causeNoClassDefFoundError tooccur, or a crash.

RETURNS:

Returns a class object from a fully-qualified name, orNULL if the class cannot be found.

THROWS:

ClassFormatError: if the class data does not specify avalid class.

ClassCircularityError: if a class or interface would beits own superclass or superinterface.

NoClassDefFoundError: if no definition for a requestedclass or interface can be found.

OutOfMemoryError: if the system runs out of memory.


GetSuperclass

jclass GetSuperclass(JNIEnv *env, jclass clazz);

Ifclazz represents any class other than the classObject, then this function returns the object thatrepresents the superclass of the class specified byclazz.

Ifclazz specifies the classObject, orclazz represents an interface, this function returnsNULL.

LINKAGE:

Index 10 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

clazz: a Java class object, must not beNULL.

RETURNS:

Returns the superclass of the class represented byclazz, orNULL.


IsAssignableFrom

jboolean IsAssignableFrom(JNIEnv *env, jclass clazz1, jclass clazz2);

Determines whether an object ofclazz1 can be safelycast toclazz2.

LINKAGE:

Index 11 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

clazz1: the first class argument, must not beNULL.

clazz2: the second class argument, must not beNULL.

RETURNS:

ReturnsJNI_TRUE if either of the following is true:


Module Operations


GetModule

jobject GetModule(JNIEnv *env, jclass clazz);

Returns thejava.lang.Module object for the module thatthe class is a member of. If the class is not in a named module then theunnamed module of the class loader for the class is returned. If theclass represents an array type then this function returns theModule object for the element type. If the class representsa primitive type orvoid, then theModuleobject for thejava.base module is returned.

LINKAGE:

Index 233 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

clazz: a Java class object, must not beNULL.

RETURNS:

Returns the module that the class or interface is a member of.

SINCE:

JDK/JRE 9


Thread Operations


IsVirtualThread

jboolean IsVirtualThread(JNIEnv *env, jobject obj);

Tests whether an object is a virtual Thread.

LINKAGE:

Index 234 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

obj: a Java object, possibly aNULLvalue.

RETURNS:

Returns JNI_TRUE if the object is a virtual Thread.

SINCE:

JDK/JRE 21


Exceptions


Throw

jint Throw(JNIEnv *env, jthrowable obj);

Causes ajava.lang.Throwable object to be thrown.

LINKAGE:

Index 13 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

obj: ajava.lang.Throwable object, must notbeNULL.

RETURNS:

Returns 0 on success; a negative value on failure.

THROWS:

Thejava.lang.Throwable objectobj.


ThrowNew

jint ThrowNew(JNIEnv *env, jclass clazz, const char *message);

Constructs an exception object from the specified class with themessage specified bymessage and causes that exception tobe thrown.

LINKAGE:

Index 14 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

clazz: a subclass ofjava.lang.Throwable,must not beNULL.

message: the message used to construct thejava.lang.Throwable object. The string is encoded inmodified UTF-8. This value may beNULL.

RETURNS:

Returns 0 on success; a negative value on failure.

THROWS:

The newly constructedjava.lang.Throwable object.


ExceptionOccurred

jthrowable ExceptionOccurred(JNIEnv *env);

Determines if an exception is being thrown. The exception stays beingthrown until either the native code callsExceptionClear(),or the Java code handles the exception.

If the exception object currently being thrown is not needed then theExceptionCheck() method is asimpler alternative to use.

LINKAGE:

Index 15 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

RETURNS:

Returns the exception object that is currently in the process ofbeing thrown, orNULL if no exception is currently beingthrown.


ExceptionDescribe

void ExceptionDescribe(JNIEnv *env);

Prints an exception and a backtrace of the stack to a systemerror-reporting channel, such asstderr. The exceptionbeing thrown is cleared as a side-effect of calling this function. Thisis a convenience routine provided for debugging.

LINKAGE:

Index 16 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.


ExceptionClear

void ExceptionClear(JNIEnv *env);

Clears any exception that is currently being thrown. If no exceptionis currently being thrown, this routine has no effect.

LINKAGE:

Index 17 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.


FatalError

void FatalError(JNIEnv *env, const char *msg);

Raises a fatal error and does not expect the VM to recover. Thisfunction does not return.

LINKAGE:

Index 18 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

msg: an error message. The string is encoded in modifiedUTF-8. May be aNULL value.


ExceptionCheck

jboolean ExceptionCheck(JNIEnv *env);

Determines if an exception is being thrown. The exception stays beingthrown until either the native code callsExceptionClear(),or the Java code handles the exception.

This is a convenience function to check if an exception is beingthrown, without creating a local reference to the exception object (seeExceptionOccurred()).

LINKAGE:

Index 228 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

RETURNS:

ReturnsJNI_TRUE when there is an exception beingthrown; otherwise, returnsJNI_FALSE.


Global and Local References

Global References


NewGlobalRef

jobject NewGlobalRef(JNIEnv *env, jobject obj);

Creates a new global reference to the object referred to by theobj argument. Theobj argument may be a globalor local reference. Global references must be explicitly disposed of bycallingDeleteGlobalRef().

LINKAGE:

Index 21 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

obj: a global or local reference. May be aNULL value, in which case this function will returnNULL.

RETURNS:

Returns a global reference to the givenobj.

May returnNULL if:


DeleteGlobalRef

void DeleteGlobalRef(JNIEnv *env, jobject globalRef);

Deletes the global reference pointed to byglobalRef.

LINKAGE:

Index 22 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

globalRef: a global reference. May be aNULL value, in which case this function does nothing.


Local References

Local references are valid for the duration of a native method call.They are freed automatically after the native method returns. Each localreference costs some amount of Java Virtual Machine resource.Programmers need to make sure that native methods do not excessivelyallocate local references. Although local references are automaticallyfreed after the native method returns to Java, excessive allocation oflocal references may cause the VM to run out of memory during theexecution of a native method.


DeleteLocalRef

void DeleteLocalRef(JNIEnv *env, jobject localRef);

Deletes the local reference pointed to bylocalRef.

LINKAGE:

Index 23 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

localRef: a local reference. The function does nothingin the case of aNULL value passed here.

Note: JDK/JRE 1.1 provides theDeleteLocalRef function above so that programmers canmanually delete local references. For example, if native code iteratesthrough a potentially large array of objects and uses one element ineach iteration, it is a good practice to delete the local reference tothe no-longer-used array element before a new local reference is createdin the next iteration. As of JDK/JRE 1.2 an additional set of functionsare provided for local reference lifetime management. They are the fourfunctions listed below.


EnsureLocalCapacity

jint EnsureLocalCapacity(JNIEnv *env, jint capacity);

Ensures thatat least a given number of local references canbe created in the current thread. Returns 0 on success; otherwisereturns a negative number and throws anOutOfMemoryError.

Before it enters a native method, the VM automatically ensures thatat least16 local references can be created.

For backward compatibility, the VM allocates local references beyondthe ensured capacity. (As a debugging support, the VM may give the userwarnings that too many local references are being created. In the JDK,the programmer can supply the-verbose:jni command lineoption to turn on these messages.) The VM callsFatalErrorif no more local references can be created beyond the ensuredcapacity.

Some Java Virtual Machine implementations may choose to limit themaximumcapacity, which may cause the function to return anerror (e.g.JNI_ERR orJNI_EINVAL). TheHotSpot JVM implementation, for example, uses the-XX:+MaxJNILocalCapacity flag (default: 65536).

LINKAGE:

Index 26 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

capacity: the minimum number of required localreferences. Must be >= 0.

RETURNS:

JNI_OK upon succcess.

SINCE:

JDK/JRE 1.2


PushLocalFrame

jint PushLocalFrame(JNIEnv *env, jint capacity);

Creates a new local reference frame, in which at least a given numberof local references can be created. Returns 0 on success, a negativenumber and throwsOutOfMemoryError on failure.

Note that local references already created in previous local framesare still valid in the current local frame.

As withEnsureLocalCapacity, some Java Virtual Machineimplementations may choose to limit the maximumcapacity,which may cause the function to return an error.

LINKAGE:

Index 19 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

capacity: the minimum number of required localreferences. Must be > 0.

RETURNS:

JNI_OK upon succcess.

SINCE:

JDK/JRE 1.2


PopLocalFrame

jobject PopLocalFrame(JNIEnv *env, jobject result);

Pops off the current local reference frame, frees all the localreferences, and returns a local reference in the previous localreference frame for the givenresult object.

PassNULL asresult if you do not need toreturn a reference to the previous frame.

LINKAGE:

Index 20 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

result: an object to be passed to the previous localreference frame, may beNULL.

RETURNS:

Returns a local reference in the previous local reference frame forthe givenresult object, orNULL if the givenresult object wasNULL.

SINCE:

JDK/JRE 1.2


NewLocalRef

jobject NewLocalRef(JNIEnv *env, jobject ref);

Creates a new local reference that refers to the same object asref. The givenref may be a global, a localreference orNULL.

LINKAGE:

Index 25 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

ref: a reference to the object for which the functioncreates a new local reference. May be aNULL value.

RETURNS:

Returns a new local reference that refers to the same object asref.

May returnNULL if:

SINCE:

JDK/JRE 1.2


Weak Global References

Weak global references are a special kind of global reference. Unlikenormal global references, a weak global reference allows the underlyingJava object to be garbage collected. Weak global references may be usedin any situation where global or local references are used.

Weak global references are related to Java phantom references(java.lang.ref.PhantomReference). A weak global referenceto a specific object is treated as a phantom reference referring to thatobject when determining whether the object isphantom reachable(seejava.lang.ref). Such a weak global reference willbecome functionally equivalent toNULL at the same time asaPhantomReference referring to that same object would becleared by the garbage collector.

Since garbage collection may occur while native methods are running,objects referred to by weak global references can be freed at any time.While weak global referencescan be used where globalreferences are used, it is generally inappropriate to do so, as they maybecome functionally equivalent toNULL without notice.

IsSameObject can be used to compare a weak globalreference to a non-NULL local or global reference. If theobjects are the same, the weak global reference won't becomefunctionally equivalent toNULL so long as the otherreference has not been deleted.

IsSameObject can also be used to compare a weak globalreference toNULL to determine whether the underlyingobject has been freed. However, programmers should not rely on thischeck to determine whether a weak global reference may be used (as anon-NULL reference) in any future JNI function call, sincean intervening garbage collection could change the weak globalreference.

Instead, it is recommended that a (strong) local or global referenceto the underlying object be acquired using one of the JNI functionsNewLocalRef orNewGlobalRef. These functionswill returnNULL if the object has been freed. Otherwise,the new reference will prevent the underlying object from being freed.The new reference, if non-NULL, can then be used to accessthe underlying object, and deleted when such access is no longerneeded.


NewWeakGlobalRef

jweak NewWeakGlobalRef(JNIEnv *env, jobject obj);

Creates a new weak global reference. The weak global reference willnot prevent garbage collection of the given object.IsSameObject may be used to test if the object referred toby the reference has been freed.

LINKAGE:

Index 226 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

obj: the object to create a global weak referencefor.

RETURNS:

Return a global weak reference to the givenobj.

May returnNULL if:

THROWS:

OutOfMemoryError if the system runs out of memory.

SINCE:

JDK/JRE 1.2


DeleteWeakGlobalRef

void DeleteWeakGlobalRef(JNIEnv *env, jweak obj);

Delete the VM resources needed for the given weak globalreference.

LINKAGE:

Index 227 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

obj: global weak reference to delete. This function doesnothing if passedNULL.

SINCE:

JDK/JRE 1.2


Object Operations


AllocObject

jobject AllocObject(JNIEnv *env, jclass clazz);

Allocates a new Java objectwithout invoking any of theconstructors for the object. Returns a reference to theobject.

Note: The Java Language Specification, "ImplementingFinalization" (JLS§12.6.1) states: "An object o is not finalizable until itsconstructor has invoked the constructor for Object on o and thatinvocation has completed successfully". Since AllocObject() does notinvoke a constructor, objects created with this function are noteligible for finalization.

The clazz argument must not refer to an array class.

LINKAGE:

Index 27 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

clazz: a reference to a Java class object, must not beNULL.

RETURNS:

Returns a Java object, orNULL if the object cannot beconstructed.

THROWS:

InstantiationException: if the class is an interface oran abstract class.

OutOfMemoryError: if the system runs out of memory.


NewObject, NewObjectA,NewObjectV

jobject NewObject(JNIEnv *env, jclass clazz, jmethodID methodID, ...);

jobject NewObjectA(JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);

jobject NewObjectV(JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);

Constructs a new Java object. The method ID indicates whichconstructor method to invoke. This ID must be obtained by callingGetMethodID() with<init> as the methodname andvoid (V) as the return type.

Theclazz argument must not refer to an array class.

NewObject

Programmers place all arguments that are to be passed to theconstructor immediately following themethodID argument.NewObject() accepts these arguments and passes them to theJava method that the programmer wishes to invoke.

LINKAGE:

Index 28 in the JNIEnv interface function table.

NewObjectA

Programmers place all arguments that are to be passed to theconstructor in anargs array ofjvalues thatimmediately follows themethodID argument.NewObjectA() accepts the arguments in this array, and, inturn, passes them to the Java method that the programmer wishes toinvoke.

LINKAGE:

Index 30 in the JNIEnv interface function table.

NewObjectV

Programmers place all arguments that are to be passed to theconstructor in anargs argument of typeva_list that immediately follows themethodIDargument.NewObjectV() accepts these arguments, and, inturn, passes them to the Java method that the programmer wishes toinvoke.

LINKAGE:

Index 29 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

clazz: a reference to a Java class object, must not beNULL.

methodID: the method ID of the constructor.

Additional Parameter forNewObject:

arguments to the constructor.

Additional Parameter forNewObjectA:

args: an array of arguments to the constructor.

Additional Parameter forNewObjectV:

args: ava_list of arguments to theconstructor.

RETURNS:

Returns a Java object, orNULL if the object cannot beconstructed.

THROWS:

InstantiationException: if the class is an interface oran abstract class.

OutOfMemoryError: if the system runs out of memory.

Any exceptions thrown by the constructor.


GetObjectClass

jclass GetObjectClass(JNIEnv *env, jobject obj);

Returns the class of an object.

LINKAGE:

Index 31 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

obj: a Java object, must not beNULL.

RETURNS:

Returns a Java class object.


GetObjectRefType

jobjectRefType GetObjectRefType(JNIEnv* env, jobject obj);

Returns the type of the object referred to by theobjargument. The argumentobj can either be a local, global orweak global reference, orNULL.

LINKAGE:

Index 232 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

obj: a local, global or weak global reference.

RETURNS:

The functionGetObjectRefType returns one of thefollowing enumerated values defined as ajobjectRefType:

JNIInvalidRefType    = 0JNILocalRefType      = 1JNIGlobalRefType     = 2JNIWeakGlobalRefType = 3

If the argumentobj is a weak global reference type, thereturn will beJNIWeakGlobalRefType.

If the argumentobj is a global reference type, thereturn value will beJNIGlobalRefType.

If the argumentobj is a local reference type, thereturn will beJNILocalRefType.

If theobj argument is not a valid reference, the returnvalue for this function will beJNIInvalidRefType.

An invalid reference is a reference which is not a valid handle. Thatis, theobj pointer address does not point to a location inmemory which has been allocated from one of the Ref creation functionsor returned from a JNI function.

As such,NULL would be an invalid reference andGetObjectRefType(env,NULL) would returnJNIInvalidRefType.

On the other hand, a null reference, which is a reference that pointsto a null, would return the type of reference that the null referencewas originally created as.

GetObjectRefType cannot be used on deletedreferences.

Since references are typically implemented as pointers to memory datastructures that can potentially be reused by any of the referenceallocation services in the VM, once deleted, it is not specified whatvalue theGetObjectRefType will return.

SINCE:

JDK/JRE 1.6


IsInstanceOf

jboolean IsInstanceOf(JNIEnv *env, jobject obj, jclass clazz);

Tests whether an object is an instance of a class.

LINKAGE:

Index 32 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

obj: a Java object, possibly aNULLvalue.

clazz: a Java class object, must not beNULL.

RETURNS:

ReturnsJNI_TRUE ifobj can be cast toclazz; otherwise, returnsJNI_FALSE. ANULL object can be cast to any class.


IsSameObject

jboolean IsSameObject(JNIEnv *env, jobject ref1, jobject ref2);

Tests whether two references refer to the same Java object.

LINKAGE:

Index 24 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

ref1: a Java object, may beNULL.

ref2: a Java object, may beNULL.

RETURNS:

ReturnsJNI_TRUE ifref1 andref2 refer to the same Java object, or are bothNULL; otherwise, returnsJNI_FALSE.


Accessing Fields of Objects


GetFieldID

jfieldID GetFieldID(JNIEnv *env, jclass clazz, const char *name, const char *sig);

Returns the field ID for an instance (nonstatic) field of a class.The field is specified by its name and signature. TheGet<type>Field andSet<type>Field familiesof accessor functions use field IDs to retrieve object fields.

GetFieldID() causes an uninitialized class to beinitialized.

GetFieldID() cannot be used to obtain the length fieldof an array. UseGetArrayLength() instead.

LINKAGE:

Index 94 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

clazz: a Java class object, must not beNULL.

name: the field name in a 0-terminated modified UTF-8string, must not beNULL.

sig: the field signature in a 0-terminated modifiedUTF-8 string, must not beNULL.

RETURNS:

Returns a field ID, orNULL if the operation fails.

THROWS:

NoSuchFieldError: if the specified field cannot befound.

ExceptionInInitializerError: if the class initializerfails due to an exception.

OutOfMemoryError: if the system runs out of memory.


Get<type>Field Routines

NativeTypeGet<type>Field(JNIEnv *env, jobject obj, jfieldID fieldID);

This family of accessor routines returns the value of an instance(nonstatic) field of an object. The field to access is specified by afield ID obtained by callingGetFieldID().

The following table describes theGet<type>Fieldroutine name and result type. You should replacetype inGet<type>Field with the Java type of the field, or useone of the actual routine names from the table, and replaceNativeType with the corresponding native type for thatroutine.

Get<type>Field Family of AccessorRoutines
Get<type>Field Routine NameNative Type
GetObjectField()jobject
GetBooleanField()jboolean
GetByteField()jbyte
GetCharField()jchar
GetShortField()jshort
GetIntField()jint
GetLongField()jlong
GetFloatField()jfloat
GetDoubleField()jdouble

LINKAGE:

Indices in the JNIEnv interface function table:

Get<type>Field Family of AccessorRoutines
Get<type>Field RoutineNameIndex
GetObjectField()95
GetBooleanField()96
GetByteField()97
GetCharField()98
GetShortField()99
GetIntField()100
GetLongField()101
GetFloatField()102
GetDoubleField()103

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

obj: a Java object, must not beNULL.

fieldID: a valid field ID.

RETURNS:

Returns the content of the field.


Set<type>Field Routines

voidSet<type>Field(JNIEnv *env, jobject obj, jfieldID fieldID,NativeTypevalue);

This family of accessor routines sets the value of an instance(nonstatic) field of an object. The field to access is specified by afield ID obtained by callingGetFieldID().

The following table describes theSet<type>Fieldroutine name and value type. You should replacetype inSet<type>Field with the Java type of the field, or useone of the actual routine names from the table, and replaceNativeType with the corresponding native type for thatroutine.

Set<type>Field Family of AccessorRoutines
Set<type>Field RoutineNative Type
SetObjectField()jobject
SetBooleanField()jboolean
SetByteField()jbyte
SetCharField()jchar
SetShortField()jshort
SetIntField()jint
SetLongField()jlong
SetFloatField()jfloat
SetDoubleField()jdouble

LINKAGE:

Indices in the JNIEnv interface function table.

Set<type>Field Family of AccessorRoutines
Set<type>Field RoutineIndex
SetObjectField()104
SetBooleanField()105
SetByteField()106
SetCharField()107
SetShortField()108
SetIntField()109
SetLongField()110
SetFloatField()111
SetDoubleField()112

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

obj: a Java object, must not beNULL.

fieldID: a valid field ID.

value: the new value of the field.


Calling Instance Methods

When calling methods from native code be mindful of whether thosemethods may becaller-sensitive.


GetMethodID

jmethodID GetMethodID(JNIEnv *env, jclass clazz, const char *name, const char *sig);

Returns the method ID for an instance (nonstatic) method of a classor interface. The method may be defined in one of theclazz’s supertypes and inherited byclazz. Themethod is determined by its name and signature.

GetMethodID() causes an uninitialized class to beinitialized.

To obtain the method ID of a constructor, supply<init> as the method name andvoid(V) as the return type.

LINKAGE:

Index 33 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

clazz: a Java class object, must not beNULL.

name: the method name in a 0-terminated modified UTF-8string, must not beNULL.

sig: the method signature in 0-terminated modified UTF-8string, must not beNULL.

RETURNS:

Returns a method ID, orNULL if the specified methodcannot be found.

THROWS:

NoSuchMethodError: if the specified method cannot befound.

ExceptionInInitializerError: if the class initializerfails due to an exception.

OutOfMemoryError: if the system runs out of memory.


Call<type>MethodRoutines, Call<type>MethodA Routines, Call<type>MethodVRoutines

NativeTypeCall<type>Method(JNIEnv *env, jobject obj, jmethodID methodID, ...);

NativeTypeCall<type>MethodA(JNIEnv *env, jobject obj, jmethodID methodID, const jvalue *args);

NativeTypeCall<type>MethodV(JNIEnv *env, jobject obj, jmethodID methodID, va_list args);

Methods from these three families of operations are used to call aJava instance method from a native method.They only differ in theirmechanism for passing parameters to the methods that they call.

These families of operations invoke an instance (nonstatic) method ona Java object, according to the specified method ID. ThemethodID argument must be obtained by callingGetMethodID().

When these functions are used to call private methods andconstructors, the method ID must be derived from the real class ofobj, not from one of its superclasses.

Call<type>Method Routines

Programmers place all arguments that are to be passed to the methodimmediately following themethodID argument. TheCall<type>Method routine accepts these arguments andpasses them to the Java method that the programmer wishes to invoke.

Call<type>MethodA Routines

Programmers place all arguments to the method in anargsarray ofjvalues that immediately follows themethodID argument. TheCall<type>MethodAroutine accepts the arguments in this array, and, in turn, passes themto the Java method that the programmer wishes to invoke.

Call<type>MethodV Routines

Programmers place all arguments to the method in anargsargument of typeva_list that immediately follows themethodID argument. TheCall<type>MethodVroutine accepts the arguments, and, in turn, passes them to the Javamethod that the programmer wishes to invoke.

The following table describes each of the method calling routinesaccording to their result type. You should replacetype inCall<type>Method with the Java type of the method you arecalling (or use one of the actual method calling routine names from thetable) and replaceNativeType with the corresponding nativetype for that routine.

Instance Method Calling Routines
Call<type>Method RoutineNameNative Type
CallVoidMethod()
CallVoidMethodA()
CallVoidMethodV()
void
CallObjectMethod()
CallObjectMethodA()
CallObjectMethodV()
jobject
CallBooleanMethod()
CallBooleanMethodA()
CallBooleanMethodV()
jboolean
CallByteMethod()
CallByteMethodA()
CallByteMethodV()
jbyte
CallCharMethod()
CallCharMethodA()
CallCharMethodV()
jchar
CallShortMethod()
CallShortMethodA()
CallShortMethodV()
jshort
CallIntMethod()
CallIntMethodA()
CallIntMethodV()
jint
CallLongMethod()
CallLongMethodA()
CallLongMethodV()
jlong
CallFloatMethod()
CallFloatMethodA()
CallFloatMethodV()
jfloat
CallDoubleMethod()
CallDoubleMethodA()
CallDoubleMethodV()
jdouble

LINKAGE:

Indices in the JNIEnv interface function table:

Instance Method Calling Routines
Call<type>Method RoutineNameIndex
CallVoidMethod()
CallVoidMethodA()
CallVoidMethodV()
61
63
62
CallObjectMethod()
CallObjectMethodA()
CallObjectMethodV()
34
36
35
CallBooleanMethod()
CallBooleanMethodA()
CallBooleanMethodV()
37
39
38
CallByteMethod()
CallByteMethodA()
CallByteMethodV()
40
42
41
CallCharMethod()
CallCharMethodA()
CallCharMethodV()
43
45
44
CallShortMethod()
CallShortMethodA()
CallShortMethodV()
46
48
47
CallIntMethod()
CallIntMethodA()
CallIntMethodV()
49
51
50
CallLongMethod()
CallLongMethodA()
CallLongMethodV()
52
54
53
CallFloatMethod()
CallFloatMethodA()
CallFloatMethodV()
55
57
56
CallDoubleMethod()
CallDoubleMethodA()
CallDoubleMethodV()
58
60
59

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

obj: a Java object, must not beNULL.

methodID: a valid method ID.

AdditionalParameter for Call<type>Method Routines:

arguments to the Java method.

AdditionalParameter for Call<type>MethodA Routines:

args: an array of arguments.

AdditionalParameter for Call<type>MethodV Routines:

args: ava_list of arguments.

RETURNS:

Returns the result of calling the Java method.

THROWS:

Exceptions raised during the execution of the Java method.


CallNonvirtual<type>MethodRoutines, CallNonvirtual<type>MethodA Routines,CallNonvirtual<type>MethodV Routines

NativeTypeCallNonvirtual<type>Method(JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);

NativeTypeCallNonvirtual<type>MethodA(JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, const jvalue *args);

NativeTypeCallNonvirtual<type>MethodV(JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, va_list args);

These families of operations invoke an instance (nonstatic) method ona Java object, according to the specified class and method ID. ThemethodID argument must be obtained by callingGetMethodID() on the classclazz.

TheCallNonvirtual<type>Method families of routinesand theCall<type>Method families of routines aredifferent.Call<type>Method routines invoke the methodbased on the class or interface of the object, whileCallNonvirtual<type>Method routines invoke the methodbased on the class, designated by theclazz parameter, fromwhich the method ID is obtained. The method ID must be obtained from thereal class of the object or from one of its supertypes.

CallNonvirtual<type>Method routines are the mechanismfor invoking"default interface methods" introduced in Java8.

CallNonvirtual<type>MethodRoutines

Programmers place all arguments that are to be passed to the methodimmediately following themethodID argument. TheCallNonvirtual<type>Method routine accepts thesearguments and passes them to the Java method that the programmer wishesto invoke.

CallNonvirtual<type>MethodARoutines

Programmers place all arguments to the method in anargsarray ofjvalues that immediately follows themethodID argument. TheCallNonvirtual<type>MethodA routine accepts the argumentsin this array, and, in turn, passes them to the Java method that theprogrammer wishes to invoke.

CallNonvirtual<type>MethodVRoutines

Programmers place all arguments to the method in anargsargument of typeva_list that immediately follows themethodID argument. TheCallNonvirtualMethodVroutine accepts the arguments, and, in turn, passes them to the Javamethod that the programmer wishes to invoke.

The following table describes each of the method calling routinesaccording to their result type. You should replacetype inCallNonvirtual<type>Method with the Java type of themethod, or use one of the actual method calling routine names from thetable, and replaceNativeType with the corresponding nativetype for that routine.

CallNonvirtual<type>Method Routines
CallNonvirtual<type>MethodRoutine NameNative Type
CallNonvirtualVoidMethod()
CallNonvirtualVoidMethodA()
CallNonvirtualVoidMethodV()
void
CallNonvirtualObjectMethod()
CallNonvirtualObjectMethodA()
CallNonvirtualObjectMethodV()
jobject
CallNonvirtualBooleanMethod()
CallNonvirtualBooleanMethodA()
CallNonvirtualBooleanMethodV()
jboolean
CallNonvirtualByteMethod()
CallNonvirtualByteMethodA()
CallNonvirtualByteMethodV()
jbyte
CallNonvirtualCharMethod()
CallNonvirtualCharMethodA()
CallNonvirtualCharMethodV()
jchar
CallNonvirtualShortMethod()
CallNonvirtualShortMethodA()
CallNonvirtualShortMethodV()
jshort
CallNonvirtualIntMethod()
CallNonvirtualIntMethodA()
CallNonvirtualIntMethodV()
jint
CallNonvirtualLongMethod()
CallNonvirtualLongMethodA()
CallNonvirtualLongMethodV()
jlong
CallNonvirtualFloatMethod()
CallNonvirtualFloatMethodA()
CallNonvirtualFloatMethodV()
jfloat
CallNonvirtualDoubleMethod()
CallNonvirtualDoubleMethodA()
CallNonvirtualDoubleMethodV()
jdouble

LINKAGE:

Indices in the JNIEnv interface function table.

CallNonvirtual<type>Method Routines
CallNonvirtual<type>MethodRoutine NameIndex
CallNonvirtualVoidMethod()
CallNonvirtualVoidMethodA()
CallNonvirtualVoidMethodV()
91
93
92
CallNonvirtualObjectMethod()
CallNonvirtualObjectMethodA()
CallNonvirtualObjectMethodV()
64
66
65
CallNonvirtualBooleanMethod()
CallNonvirtualBooleanMethodA()
CallNonvirtualBooleanMethodV()
67
69
68
CallNonvirtualByteMethod()
CallNonvirtualByteMethodA()
CallNonvirtualByteMethodV()
70
72
71
CallNonvirtualCharMethod()
CallNonvirtualCharMethodA()
CallNonvirtualCharMethodV()
73
75
74
CallNonvirtualShortMethod()
CallNonvirtualShortMethodA()
CallNonvirtualShortMethodV()
76
78
77
CallNonvirtualIntMethod()
CallNonvirtualIntMethodA()
CallNonvirtualIntMethodV()
79
81
80
CallNonvirtualLongMethod()
CallNonvirtualLongMethodA()
CallNonvirtualLongMethodV()
82
84
83
CallNonvirtualFloatMethod()
CallNonvirtualFloatMethodA()
CallNonvirtualFloatMethodV()
85
87
86
CallNonvirtualDoubleMethod()
CallNonvirtualDoubleMethodA()
CallNonvirtualDoubleMethodV()
88
90
89

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

clazz: a Java class, must not beNULL.

obj: a Java object, must not beNULL.

methodID: a method ID.

AdditionalParameter for CallNonvirtual<type>Method Routines:

arguments to the Java method.

AdditionalParameter for CallNonvirtual<type>MethodA Routines:

args: an array of arguments.

AdditionalParameter for CallNonvirtual<type>MethodV Routines:

args: ava_list of arguments.

RETURNS:

Returns the result of calling the Java method.

THROWS:

Exceptions raised during the execution of the Java method.


Accessing Static Fields


GetStaticFieldID

jfieldID GetStaticFieldID(JNIEnv *env, jclass clazz, const char *name, const char *sig);

Returns the field ID for a static field of a class. The field isspecified by its name and signature. TheGetStatic<type>Field andSetStatic<type>Field families of accessor functions usefield IDs to retrieve static fields.

GetStaticFieldID() causes an uninitialized class to beinitialized.

LINKAGE:

Index 144 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

clazz: a Java class object, must not beNULL.

name: the static field name in a 0-terminated modifiedUTF-8 string, must not beNULL.

sig: the field signature in a 0-terminated modifiedUTF-8 string, must not beNULL.

RETURNS:

Returns a field ID, orNULL if the specified staticfield cannot be found.

THROWS:

NoSuchFieldError: if the specified static field cannotbe found.

ExceptionInInitializerError: if the class initializerfails due to an exception.

OutOfMemoryError: if the system runs out of memory.


GetStatic<type>FieldRoutines

NativeTypeGetStatic<type>Field(JNIEnv *env, jclass clazz, jfieldID fieldID);

This family of accessor routines returns the value of a static fieldof an object. The field to access is specified by a field ID, which isobtained by callingGetStaticFieldID().

The following table describes the family of get routine names andresult types. You should replacetype inGetStatic<type>Field with the Java type of the field, orone of the actual static field accessor routine names from the table,and replaceNativeType with the corresponding native type forthat routine.

GetStatic<type>Field Family of AccessorRoutines
GetStatic<type>FieldRoutine NameNative Type
GetStaticObjectField()jobject
GetStaticBooleanField()jboolean
GetStaticByteField()jbyte
GetStaticCharField()jchar
GetStaticShortField()jshort
GetStaticIntField()jint
GetStaticLongField()jlong
GetStaticFloatField()jfloat
GetStaticDoubleField()jdouble

LINKAGE:

Indices in the JNIEnv interface function table.

GetStatic<type>Field Family of AccessorRoutines
GetStatic<type>FieldRoutine NameIndex
GetStaticObjectField()145
GetStaticBooleanField()146
GetStaticByteField()147
GetStaticCharField()148
GetStaticShortField()149
GetStaticIntField()150
GetStaticLongField()151
GetStaticFloatField()152
GetStaticDoubleField()153

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

clazz: a Java class object, must not beNULL.

fieldID: a valid static field ID.

RETURNS:

Returns the content of the static field.


SetStatic<type>FieldRoutines

voidSetStatic<type>Field(JNIEnv *env, jclass clazz, jfieldID fieldID,NativeTypevalue);

This family of accessor routines sets the value of a static field ofan object. The field to access is specified by a field ID, which isobtained by callingGetStaticFieldID().

The following table describes the set routine name and value types.You should replacetype inSetStatic<type>Fieldwith the Java type of the field, or one of the actual set static fieldroutine names from the table, and replaceNativeType with thecorresponding native type for that routine.

SetStatic<type>Field Family of AccessorRoutines
SetStatic<type>FieldRoutine NameNativeType
SetStaticObjectField()jobject
SetStaticBooleanField()jboolean
SetStaticByteField()jbyte
SetStaticCharField()jchar
SetStaticShortField()jshort
SetStaticIntField()jint
SetStaticLongField()jlong
SetStaticFloatField()jfloat
SetStaticDoubleField()jdouble

LINKAGE:

Indices in the JNIEnv interface function table.

SetStatic<type>Field Family of AccessorRoutines
SetStatic<type>FieldRoutine NameIndex
SetStaticObjectField()154
SetStaticBooleanField()155
SetStaticByteField()156
SetStaticCharField()157
SetStaticShortField()158
SetStaticIntField()159
SetStaticLongField()160
SetStaticFloatField()161
SetStaticDoubleField()162

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

clazz: a Java class object, must not beNULL.

fieldID: a valid static field ID.

value: the new value of the field.


Calling Static Methods

When calling methods from native code be mindful of whether thosemethods may becaller-sensitive.


GetStaticMethodID

jmethodID GetStaticMethodID(JNIEnv *env, jclass clazz, const char *name, const char *sig);

Returns the method ID for a static method of a class. The method isspecified by its name and signature.

GetStaticMethodID() causes an uninitialized class to beinitialized.

LINKAGE:

Index 113 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

clazz: a Java class object, must not beNULL.

name: the static method name in a 0-terminated modifiedUTF-8 string, must not beNULL.

sig: the method signature in a 0-terminated modifiedUTF-8 string, must not beNULL.

RETURNS:

Returns a method ID, orNULL if the operation fails.

THROWS:

NoSuchMethodError: if the specified static method cannotbe found.

ExceptionInInitializerError: if the class initializerfails due to an exception.

OutOfMemoryError: if the system runs out of memory.


CallStatic<type>MethodRoutines, CallStatic<type>MethodA Routines,CallStatic<type>MethodV Routines

NativeTypeCallStatic<type>Method(JNIEnv *env, jclass clazz, jmethodID methodID, ...);

NativeTypeCallStatic<type>MethodA(JNIEnv *env, jclass clazz, jmethodID methodID, jvalue *args);

NativeTypeCallStatic<type>MethodV(JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);

This family of operations invokes a static method on a Java object,according to the specified method ID. ThemethodID argumentmust be obtained by callingGetStaticMethodID().

The method ID must be derived fromclazz, not from oneof its superclasses.

CallStatic<type>MethodRoutines

Programmers should place all arguments that are to be passed to themethod immediately following themethodID argument. TheCallStatic<type>Method routine accepts these argumentsand passes them to the Java method that the programmer wishes toinvoke.

CallStatic<type>MethodARoutines

Programmers should place all arguments to the method in anargs array ofjvalues that immediately followsthemethodID argument. TheCallStaticMethodAroutine accepts the arguments in this array, and, in turn, passes themto the Java method that the programmer wishes to invoke.

CallStatic<type>MethodVRoutines

Programmers should place all arguments to the method in anargs argument of typeva_list that immediatelyfollows themethodID argument. TheCallStaticMethodV routine accepts the arguments, and, in turn,passes them to the Java method that the programmer wishes to invoke.

The following table describes each of the method calling routinesaccording to their result types. You should replacetype inCallStatic<type>Method with the Java type of the method,or one of the actual method calling routine names from the table, andreplaceNativeType with the corresponding native type for thatroutine.

CallStatic<type>Method CallingRoutines
CallStatic<type>MethodRoutine NameNative Type
CallStaticVoidMethod()
CallStaticVoidMethodA()
CallStaticVoidMethodV()
void
CallStaticObjectMethod()
CallStaticObjectMethodA()
CallStaticObjectMethodV()
jobject
CallStaticBooleanMethod()
CallStaticBooleanMethodA()
CallStaticBooleanMethodV()
jboolean
CallStaticByteMethod()
CallStaticByteMethodA()
CallStaticByteMethodV()
jbyte
CallStaticCharMethod()
CallStaticCharMethodA()
CallStaticCharMethodV()
jchar
CallStaticShortMethod()
CallStaticShortMethodA()
CallStaticShortMethodV()
jshort
CallStaticIntMethod()
CallStaticIntMethodA()
CallStaticIntMethodV()
jint
CallStaticLongMethod()
CallStaticLongMethodA()
CallStaticLongMethodV()
jlong
CallStaticFloatMethod()
CallStaticFloatMethodA()
CallStaticFloatMethodV()
jfloat
CallStaticDoubleMethod()
CallStaticDoubleMethodA()
CallStaticDoubleMethodV()
jdouble

LINKAGE:

Indices in the JNIEnv interface function table.

CallStatic<type>Method CallingRoutines
CallStatic<type>MethodRoutine NameIndex
CallStaticVoidMethod()
CallStaticVoidMethodA()
CallStaticVoidMethodV()
141
143
142
CallStaticObjectMethod()
CallStaticObjectMethodA()
CallStaticObjectMethodV()
114
116
115
CallStaticBooleanMethod()
CallStaticBooleanMethodA()
CallStaticBooleanMethodV()
117
119
118
CallStaticByteMethod()
CallStaticByteMethodA()
CallStaticByteMethodV()
120
122
121
CallStaticCharMethod()
CallStaticCharMethodA()
CallStaticCharMethodV()
123
125
124
CallStaticShortMethod()
CallStaticShortMethodA()
CallStaticShortMethodV()
126
128
127
CallStaticIntMethod()
CallStaticIntMethodA()
CallStaticIntMethodV()
129
131
130
CallStaticLongMethod()
CallStaticLongMethodA()
CallStaticLongMethodV()
132
134
133
CallStaticFloatMethod()
CallStaticFloatMethodA()
CallStaticFloatMethodV()
135
137
136
CallStaticDoubleMethod()
CallStaticDoubleMethodA()
CallStaticDoubleMethodV()
138
140
139

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

clazz: a Java class object, must not beNULL.

methodID: a valid static method ID.

AdditionalParameter for CallStatic<type>Method Routines:

arguments to the static method.

AdditionalParameter for CallStatic<type>MethodA Routines:

args: an array of arguments.

AdditionalParameter for CallStatic<type>MethodV Routines:

args: ava_list of arguments.

RETURNS:

Returns the result of calling the static Java method.

THROWS:

Exceptions raised during the execution of the Java method.


String Operations

This specification makes no assumptions on how a JVM represent Javastrings internally. Strings returned from these operations:

are therefore not required to be NULL terminated. Programmers areexpected to determine buffer capacity requirements viaGetStringLength() orGetStringUTFLengthAsLong().


NewString

jstring NewString(JNIEnv *env, const jchar *unicodeChars, jsize len);

Constructs a newjava.lang.String object from an arrayof Unicode characters.

LINKAGE:

Index 163 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

unicodeChars: pointer to a Unicode string. May be aNULL value, in which caselen must be 0.

len: length of the Unicode string. May be 0.

RETURNS:

Returns a Java string object, orNULL if the stringcannot be constructed.

THROWS:

OutOfMemoryError: if the system runs out of memory.


GetStringLength

jsize GetStringLength(JNIEnv *env, jstring string);

Returns the length (the count of Unicode characters) of a Javastring.

LINKAGE:

Index 164 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

string: a Java string object, must not beNULL.

RETURNS:

Returns the length of the Java string.


GetStringChars

const jchar * GetStringChars(JNIEnv *env, jstring string, jboolean *isCopy);

Returns a pointer to the array of Unicode characters of the string.This pointer is valid untilReleaseStringChars() iscalled.

IfisCopy is notNULL, then*isCopy is set toJNI_TRUE if a copy is made;or it is set toJNI_FALSE if no copy is made.

LINKAGE:

Index 165 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

string: a Java string object, must not beNULL.

isCopy: a pointer to a boolean, may be aNULL value.

RETURNS:

Returns a pointer to a Unicode string, orNULL if theoperation fails.


ReleaseStringChars

void ReleaseStringChars(JNIEnv *env, jstring string, const jchar *chars);

Informs the VM that the native code no longer needs access tochars. Thechars argument is a pointerobtained fromstring usingGetStringChars().

LINKAGE:

Index 166 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

string: a Java string object, must not beNULL.

chars: a pointer to a Unicode string, as previouslyreturned byGetStringChars().


NewStringUTF

jstring NewStringUTF(JNIEnv *env, const char *bytes);

Constructs a newjava.lang.String object from an arrayof characters in modified UTF-8 encoding.

LINKAGE:

Index 167 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

bytes: the pointer to a modified UTF-8 string, must notbeNULL.

RETURNS:

Returns a Java string object, orNULL if the stringcannot be constructed.

THROWS:

OutOfMemoryError: if the system runs out of memory.


GetStringUTFLength(Deprecated)

jsize GetStringUTFLength(JNIEnv *env, jstring string);

Returns the length in bytes of the modified UTF-8 representation of astring.

As the capacity of ajsize variable is not sufficient tohold the length of all possible modified UTF-8 string representations(due to multi-byte encodings), this function is deprecated in favor ofGetStringUTFLengthAsLong().If the modified UTF-8 representation ofstring has a lengththat exceeds the capacity of ajsize variable, then thisfunction returns the number of bytes up to and including the lastcharacter that could be fully encoded without exceeding thatcapacity.

LINKAGE:

Index 168 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

string: a Java string object, must not beNULL.

RETURNS:

Returns the UTF-8 length of the string, as restricted by the capacityof ajsize variable.


GetStringUTFLengthAsLong

jlong GetStringUTFLengthAsLong(JNIEnv *env, jstring string);

Returns the length in bytes of the modified UTF-8 representation of astring.

LINKAGE:

Index 235 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

string: a Java string object, must not beNULL.

RETURNS:

Returns the UTF-8 length of the string.

SINCE

JDK 24


GetStringUTFChars

const char * GetStringUTFChars(JNIEnv *env, jstring string, jboolean *isCopy);

Returns a pointer to a sequence of bytes representing the string inmodified UTF-8 encoding. This sequence is valid until it is released byReleaseStringUTFChars().

IfisCopy is notNULL, then*isCopy is set toJNI_TRUE if a copy is made;or it is set toJNI_FALSE if no copy is made.

LINKAGE:

Index 169 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

string: a Java string object, must not beNULL.

isCopy: a pointer to a boolean, may be aNULL value.

RETURNS:

Returns a pointer to a modified UTF-8 string, orNULL ifthe operation fails.


ReleaseStringUTFChars

void ReleaseStringUTFChars(JNIEnv *env, jstring string, const char *utf);

Informs the VM that the native code no longer needs access toutf. Theutf argument is a pointer derivedfromstring usingGetStringUTFChars().

LINKAGE:

Index 170 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

string: a Java string object, must not beNULL.

utf: a pointer to a modified UTF-8 string, previouslyreturned byGetStringUTFChars().

Note: In JDK/JRE 1.1, programmers can get primitivearray elements in a user-supplied buffer. As of JDK/JRE 1.2 additionalset of functions are provided allowing native code to obtain charactersin Unicode (UTF-16) or modified UTF-8 encoding in a user-suppliedbuffer. See the functions below.


GetStringRegion

void GetStringRegion(JNIEnv *env, jstring str, jsize start, jsize len, jchar *buf);

Copieslen number of Unicode characters beginning atoffsetstart to the given bufferbuf.

LINKAGE:

Index 220 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

str: a Java string object, must not beNULL.

start: the index of the first unicode character in thestring to copy. Must be greater than or equal to zero, and less thanstring length ("GetStringLength()").

len: the number of unicode characters to copy. Must begreater than or equal to zero, and "start + len" must beless than string length ("GetStringLength()").

buf: the unicode character buffer into which to copy thestring region. Must not beNULL if givenlenis > 0.

THROWS:

StringIndexOutOfBoundsException: on index overflow.

SINCE:

JDK/JRE 1.2


GetStringUTFRegion

void GetStringUTFRegion(JNIEnv *env, jstring str, jsize start, jsize len, char *buf);

Translateslen number of Unicode characters beginning atoffsetstart into modified UTF-8 encoding and place theresult in the given bufferbuf.

Thelen argument specifies the number ofunicodecharacters. The resulting number of modified UTF-8 encodingcharacters may be greater than the givenlen argument.GetStringUTFLengthAsLong() may be used to determine themaximum size of the required character buffer.

Since this specification does not require the resulting string copybe NULL terminated, it is advisable to clear the given character buffer(e.g. "memset()") before using this function, in order tosafely performstrlen().

LINKAGE:

Index 221 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

str: a Java string object, must not beNULL.

start: the index of the first unicode character in thestring to copy. Must be greater than or equal to zero, and less than thestring length.

len: the number of unicode characters to copy. Must begreater than zero, and "start + len" must be less thanstring length ("GetStringLength()").

buf: the unicode character buffer into which to copy thestring region. Must not beNULL if givenlenis > 0.

THROWS:

StringIndexOutOfBoundsException: on index overflow.

SINCE:

JDK/JRE 1.2


GetStringCritical,ReleaseStringCritical

const jchar * GetStringCritical(JNIEnv *env, jstring string, jboolean *isCopy);

void ReleaseStringCritical(JNIEnv *env, jstring string, const jchar *carray);

The semantics of these two functions are similar to the existingGet/ReleaseStringChars functions. If possible, the VMreturns a pointer to string elements; otherwise, a copy is made.However, there are significant restrictions on how thesefunctions can be used. In a code segment enclosed byGet/ReleaseStringCritical calls, the native code must notissue arbitrary JNI calls, or cause the current thread to block.

The restrictions onGet/ReleaseStringCritical aresimilar to those onGet/ReleasePrimitiveArrayCritical.

LINKAGE (GetStringCritical):

Index 224 in the JNIEnv interface function table.

LINKAGE(ReleaseStingCritical):

Index 225 in the JNIEnv interface function table.

SEE ALSO:

GetStringChars

ReleaseStringChars

SINCE:

JDK/JRE 1.2


Array Operations


GetArrayLength

jsize GetArrayLength(JNIEnv *env, jarray array);

Returns the number of elements in the array.

LINKAGE:

Index 171 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

array: a Java array object, must not beNULL.

RETURNS:

Returns the length of the array.


NewObjectArray

jobjectArray NewObjectArray(JNIEnv *env, jsize length, jclass elementClass, jobject initialElement);

Constructs a new array holding objects in classelementClass. All elements are initially set toinitialElement.

LINKAGE:

Index 172 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

length: array size, must be >= 0.

elementClass: array element class, must not beNULL.

initialElement: initialization value, may be aNULL value.

RETURNS:

Returns a Java array object, orNULL if the array cannotbe constructed.

THROWS:

OutOfMemoryError: if the system runs out of memory.


GetObjectArrayElement

jobject GetObjectArrayElement(JNIEnv *env, jobjectArray array, jsize index);

Returns an element of anObject array.

LINKAGE:

Index 173 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

array: a Java array, must not beNULL.

index: array index, must be >= 0 and less than arraylength ("GetArrayLength()").

RETURNS:

Returns a Java object.

THROWS:

ArrayIndexOutOfBoundsException: ifindexdoes not specify a valid index in the array.


SetObjectArrayElement

void SetObjectArrayElement(JNIEnv *env, jobjectArray array, jsize index, jobject value);

Sets an element of anObject array.

LINKAGE:

Index 174 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

array: a Java array, must not beNULL.

index: array index, must be >= 0 and less than arraylength ("GetArrayLength()").

value: the new value, may be aNULLvalue.

THROWS:

ArrayIndexOutOfBoundsException: ifindexdoes not specify a valid index in the array.

ArrayStoreException: if the class ofvalueis not a subclass of the element class of the array.


New<PrimitiveType>ArrayRoutines

ArrayTypeNew<PrimitiveType>Array(JNIEnv *env, jsize length);

A family of operations used to construct a new primitive arrayobject. The following table describes the specific primitive arrayconstructors. You should replaceNew<PrimitiveType>Arraywith one of the actual primitive array constructor routine names fromthis table, and replace ArrayType with the corresponding array type forthat routine.

New<PrimitiveType>Array Family of ArrayConstructors
New<PrimitiveType>ArrayRoutinesArray Type
NewBooleanArray()jbooleanArray
NewByteArray()jbyteArray
NewCharArray()jcharArray
NewShortArray()jshortArray
NewIntArray()jintArray
NewLongArray()jlongArray
NewFloatArray()jfloatArray
NewDoubleArray()jdoubleArray

LINKAGE:

Indices in the JNIEnv interface function table.

New<PrimitiveType>Array Family of ArrayConstructors
New<PrimitiveType>ArrayRoutinesIndex
NewBooleanArray()175
NewByteArray()176
NewCharArray()177
NewShortArray()178
NewIntArray()179
NewLongArray()180
NewFloatArray()181
NewDoubleArray()182

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

length: the array length, must be >= 0.

RETURNS:

Returns a Java array, orNULL if the array cannot beconstructed.

THROWS:

OutOfMemoryError: if the system runs out of memory.


Get<PrimitiveType>ArrayElementsRoutines

NativeType*Get<PrimitiveType>ArrayElements(JNIEnv *env,ArrayTypearray, jboolean *isCopy);

A family of functions that returns the body of the primitive array.The result is valid until the correspondingRelease<PrimitiveType>ArrayElements() function is called.Since the returned array may be a copy of the Java array,changes made to the returned array will not necessarily be reflected inthe original array untilRelease<PrimitiveType>ArrayElements() iscalled.

IfisCopy is notNULL, then*isCopy is set toJNI_TRUE if a copy is made;or it is set toJNI_FALSE if no copy is made.

The following table describes the specific primitive array elementaccessors. You should make the following substitutions:

Regardless of how boolean arrays are represented in the Java VM,GetBooleanArrayElements() always returns a pointer tojbooleans, with each byte denoting an element (the unpackedrepresentation). All arrays of other types are guaranteed to becontiguous in memory.

Get<PrimitiveType>ArrayElements Family ofAccessor Routines
Get<PrimitiveType>ArrayElementsRoutinesArray TypeNative Type
GetBooleanArrayElements()jbooleanArrayjboolean
GetByteArrayElements()jbyteArrayjbyte
GetCharArrayElements()jcharArrayjchar
GetShortArrayElements()jshortArrayjshort
GetIntArrayElements()jintArrayjint
GetLongArrayElements()jlongArrayjlong
GetFloatArrayElements()jfloatArrayjfloat
GetDoubleArrayElements()jdoubleArrayjdouble

LINKAGE:

Indices in the JNIEnv interface function table.

Get<PrimitiveType>ArrayElements Family ofAccessor Routines
Get<PrimitiveType>ArrayElementsRoutinesIndex
GetBooleanArrayElements()183
GetByteArrayElements()184
GetCharArrayElements()185
GetShortArrayElements()186
GetIntArrayElements()187
GetLongArrayElements()188
GetFloatArrayElements()189
GetDoubleArrayElements()190

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

array: a Java array object, must not beNULL.

isCopy: a pointer to a boolean, may be aNULL value.

RETURNS:

Returns a pointer to the array elements, orNULL if theoperation fails.

THROWS:

OutOfMemoryError: if the system runs out of memory.


Release<PrimitiveType>ArrayElementsRoutines

voidRelease<PrimitiveType>ArrayElements(JNIEnv *env,ArrayTypearray,NativeType*elems, jint mode);

A family of functions that informs the VM that the native code nolonger needs access toelems. Theelemsargument is a pointer derived fromarray using thecorrespondingGet<PrimitiveType>ArrayElements() function.If necessary, this function copies back all changes made toelems to the original array.

Themode argument provides information on how the arraybuffer should be released.mode has no effect ifelems is not a copy of the elements inarray.Otherwise,mode has the following impact, as shown in thefollowing table:

Primitive Array Release Modes
modeactions
0copy back the content and free theelems buffer
JNI_COMMITcopy back the content but do not free theelems buffer
JNI_ABORTfree the buffer without copying back thepossible changes

In most cases, programmers pass "0" as themode argumentto ensure consistent behavior for both pinned and copied arrays. Theother options give the programmer more control over memory managementand should be used with extreme care. IfJNI_COMMIT ispassed as themode argument whenelems is acopy of the elements inarray, then a final call toRelease<PrimitiveType>ArrayElements passing amode argument of "0" orJNI_ABORT, should bemade to free theelems buffer.

The next table describes the specific routines that comprise thefamily of primitive array disposers. You should make the followingsubstitutions:

Release<PrimitiveType>ArrayElements Family ofArray Routines
Release<PrimitiveType>ArrayElementsRoutinesArray TypeNative Type
ReleaseBooleanArrayElements()jbooleanArrayjboolean
ReleaseByteArrayElements()jbyteArrayjbyte
ReleaseCharArrayElements()jcharArrayjchar
ReleaseShortArrayElements()jshortArrayjshort
ReleaseIntArrayElements()jintArrayjint
ReleaseLongArrayElements()jlongArrayjlong
ReleaseFloatArrayElements()jfloatArrayjfloat
ReleaseDoubleArrayElements()jdoubleArrayjdouble

LINKAGE:

Indices in the JNIEnv interface function table.

Release<PrimitiveType>ArrayElements Family ofArray Routines
Release<PrimitiveType>ArrayElementsRoutinesIndex
ReleaseBooleanArrayElements()191
ReleaseByteArrayElements()192
ReleaseCharArrayElements()193
ReleaseShortArrayElements()194
ReleaseIntArrayElements()195
ReleaseLongArrayElements()196
ReleaseFloatArrayElements()197
ReleaseDoubleArrayElements()198

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

array: a Java array object, must not beNULL.

elems: a pointer to array elements, as returned bypreviousGet<PrimitiveType>ArrayElements call.

mode: the release mode:0,JNI_COMMIT orJNI_ABORT.


Get<PrimitiveType>ArrayRegionRoutines

voidGet<PrimitiveType>ArrayRegion(JNIEnv *env,ArrayTypearray, jsize start, jsize len,NativeType*buf);

A family of functions that copies a region of a primitive array intoa buffer.

The following table describes the specific primitive array elementaccessors. You should do the following substitutions:

Get<PrimitiveType>ArrayRegion Family of ArrayAccessor Routines
Get<PrimitiveType>ArrayRegionRoutineArray TypeNative Type
GetBooleanArrayRegion()jbooleanArrayjboolean
GetByteArrayRegion()jbyteArrayjbyte
GetCharArrayRegion()jcharArrayjchar
GetShortArrayRegion()jshortArrayjshort
GetIntArrayRegion()jintArrayjint
GetLongArrayRegion()jlongArrayjlong
GetFloatArrayRegion()jfloatArrayjfloat
GetDoubleArrayRegion()jdoubleArrayjdouble

LINKAGE:

Indices in the JNIEnv interface function table.

Get<PrimitiveType>ArrayRegion Family of ArrayAccessor Routines
Get<PrimitiveType>ArrayRegionRoutineIndex
GetBooleanArrayRegion()199
GetByteArrayRegion()200
GetCharArrayRegion()201
GetShortArrayRegion()202
GetIntArrayRegion()203
GetLongArrayRegion()204
GetFloatArrayRegion()205
GetDoubleArrayRegion()206

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

array: a Java array, must not beNULL.

start: the starting index, must be greater than or equalto zero, and less than the array length(GetArrayLength()).

len: the number of elements to be copied, must begreater than or equal to zero, and "start + len" must beless than array length ("GetArrayLength()").

buf: the destination buffer, must not beNULL.

THROWS:

ArrayIndexOutOfBoundsException: if one of the indexes inthe region is not valid.


Set<PrimitiveType>ArrayRegionRoutines

voidSet<PrimitiveType>ArrayRegion(JNIEnv *env,ArrayTypearray, jsize start, jsize len, constNativeType*buf);

A family of functions that copies back a region of a primitive arrayfrom a buffer.

The following table describes the specific primitive array elementaccessors. You should make the following replacements:

Set<PrimitiveType>ArrayRegion Family of ArrayAccessor Routines
Set<PrimitiveType>ArrayRegionRoutineArray TypeNative Type
SetBooleanArrayRegion()jbooleanArrayjboolean
SetByteArrayRegion()jbyteArrayjbyte
SetCharArrayRegion()jcharArrayjchar
SetShortArrayRegion()jshortArrayjshort
SetIntArrayRegion()jintArrayjint
SetLongArrayRegion()jlongArrayjlong
SetFloatArrayRegion()jfloatArrayjfloat
SetDoubleArrayRegion()jdoubleArrayjdouble

LINKAGE:

Indices in the JNIEnv interface function table.

Set<PrimitiveType>ArrayRegion Family of ArrayAccessor Routines
Set<PrimitiveType>ArrayRegionRoutineIndex
SetBooleanArrayRegion()207
SetByteArrayRegion()208
SetCharArrayRegion()209
SetShortArrayRegion()210
SetIntArrayRegion()211
SetLongArrayRegion()212
SetFloatArrayRegion()213
SetDoubleArrayRegion()214

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

array: a Java array, must not beNULL.

start: the starting index, must be greater than or equalto zero, and less than the array length(GetArrayLength()).

len: the number of elements to be copied, must begreater than or equal to zero, and "start + len" must beless than array length ("GetArrayLength()").

buf: the source buffer, must not beNULL.

THROWS:

ArrayIndexOutOfBoundsException: if one of the indexes inthe region is not valid.

Note: Programmers can useGet/Release<primitivetype>ArrayElements functions toobtain a pointer to primitive array elements. If the VM supportspinning, the pointer to the original data is returned; otherwise, a copyis made. TheGet/Release<primitivetype>ArrayCriticalfunctions allow native code to obtain a direct pointer to array elementseven if the VM does not support pinning.


GetPrimitiveArrayCritical,ReleasePrimitiveArrayCritical

void * GetPrimitiveArrayCritical(JNIEnv *env, jarray array, jboolean *isCopy);

void ReleasePrimitiveArrayCritical(JNIEnv *env, jarray array, void *carray, jint mode);

The semantics of these two functions are very similar to the existingGet/Release<primitivetype>ArrayElements functions. Ifpossible, the VM returns a pointer to the primitive array; otherwise, acopy is made.However, there are significant restrictions on howthese functions can be used.

After callingGetPrimitiveArrayCritical, the native codeshould not run for an extended period of time before it callsReleasePrimitiveArrayCritical. We must treat the codeinside this pair of functions as running in a "critical region." Insidea critical region, native code must not call other JNI functions, or anysystem call that may cause the current thread to block and wait foranother Java thread. (For example, the current thread must not callread on a stream being written by another Java thread.)

These restrictions make it more likely that the native codewill obtain an uncopied version of the array, even if the VM does notsupport pinning. For example, a VM may temporarily disablegarbage collection when the native code is holding a pointer to an arrayobtained viaGetPrimitiveArrayCritical.

Multiple pairs ofGetPrimtiveArrayCritical andReleasePrimitiveArrayCritical may be nested. Forexample:

  jint len = (*env)->GetArrayLength(env, arr1);  jbyte *a1 = (*env)->GetPrimitiveArrayCritical(env, arr1, 0);  jbyte *a2 = (*env)->GetPrimitiveArrayCritical(env, arr2, 0);  /* We need to check in case the VM tried to make a copy. */  if (a1 == NULL || a2 == NULL) {    ... /* out of memory exception thrown */  }  memcpy(a1, a2, len);  (*env)->ReleasePrimitiveArrayCritical(env, arr2, a2, 0);  (*env)->ReleasePrimitiveArrayCritical(env, arr1, a1, 0);

Note thatGetPrimitiveArrayCritical might still make acopy of the array if the VM internally represents arrays in a differentformat. Therefore we need to check its return value againstNULL for possible out of memory situations.

GetPrimitiveArrayCritical

LINKAGE:

Linkage Index 222 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

array: a Java array, must not beNULL.

isCopy: a pointer to a boolean, may be aNULL value.

RETURNS:

Returns a pointer to the array elements, or NULL if the operationfails.

THROWS:

OutOfMemoryError: if the system runs out of memory.

SINCE:

JDK/JRE 1.2

ReleasePrimitiveArrayCritical

LINKAGE:

Linkage Index 223 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

array: a Java array, must not beNULL.

carray: critical array pointer as returned byGetPrimitiveArrayCritical.

mode: the release mode (seePrimitive Array Release Modes):0,JNI_COMMIT orJNI_ABORT. Ignored ifcarray was a not copy.

SINCE:

JDK/JRE 1.2


Registering Native Methods


RegisterNatives

jint RegisterNatives(JNIEnv *env, jclass clazz, const JNINativeMethod *methods, jint nMethods);

Registers native methods with the class specified by theclazz argument. Themethods parameterspecifies an array ofJNINativeMethod structures thatcontain the names, signatures, and function pointers of the nativemethods. Thename andsignature fields of theJNINativeMethod structure are pointers to modified UTF-8 strings. ThenMethods parameter specifies the number of native methodsin the array. TheJNINativeMethod structure is defined asfollows:

typedef struct {    char *name;    char *signature;    void *fnPtr;} JNINativeMethod;

The function pointers nominally must have the followingsignature:

ReturnType (*fnPtr)(JNIEnv *env, jobject objectOrClass, ...);

Be aware thatRegisterNatives can change the documentedbehavior of the JVM (including cryptographic algorithms, correctness,security, type safety), by changing the native code to be executed for agiven native Java method. Therefore use applications that have nativelibraries utilizing theRegisterNatives function withcaution.

LINKAGE:

Index 215 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

clazz: a Java class object, must not beNULL.

methods: the native methods in the class, must not beNULL.

nMethods: the number of native methods in the class,must be greater than zero.

RETURNS:

Returns "0" on success; returns a negative value on failure.

THROWS:

NoSuchMethodError: if a specified method cannot be foundor if the method is not native.


UnregisterNatives

jint UnregisterNatives(JNIEnv *env, jclass clazz);

Unregisters native methods of a class. The class goes back to thestate before it was linked or registered with its native methodfunctions.

This function should not be used in normal native code. Instead, itprovides special programs a way to reload and relink nativelibraries.

LINKAGE:

Index 216 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

clazz: a Java class object, must not beNULL.

RETURNS:

Returns "0" on success; returns a negative value on failure.


Monitor Operations


MonitorEnter

jint MonitorEnter(JNIEnv *env, jobject obj);

Enters the monitor associated with the object referred to byobj. Theobj reference must not beNULL.

Each Java object has a monitor associated with it. If the currentthread already owns the monitor associated withobj, itincrements a counter in the monitor indicating the number of times thisthread has entered the monitor. If the monitor associated withobj is not owned by any thread, the current thread becomesthe owner of the monitor, setting the entry count of this monitor to 1.If another thread already owns the monitor associated withobj, the current thread waits until the monitor isreleased, then tries again to gain ownership.

A monitor entered through aMonitorEnter JNI functioncall cannot be exited using themonitorexit Java virtualmachine instruction or a synchronized method return. AMonitorEnter JNI function call and amonitorenter Java virtual machine instruction may race toenter the monitor associated with the same object.

To avoid deadlocks, a monitor entered through aMonitorEnter JNI function call must be exited using theMonitorExit JNI call, unless theDetachCurrentThread call is used to implicitly release JNImonitors.

LINKAGE:

Index 217 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

obj: a Java object, must not beNULL.

RETURNS:

Returns "0" on success; returns a negative value on failure.


MonitorExit

jint MonitorExit(JNIEnv *env, jobject obj);

Exits the monitor associated with the object referred to byobj. Theobj reference must not beNULL.

The current thread must be the owner of the monitor associated withthe Java object referred to byobj. The thread decrementsthe counter indicating the number of times it has entered this monitor.If the value of the counter becomes zero, the current thread releasesthe monitor.

Native code must not useMonitorExit to exit a monitorentered through a synchronized method or amonitorenterJava virtual machine instruction.

LINKAGE:

Index 218 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

obj: a Java object, must not beNULL.

RETURNS:

Returns "0" on success; returns a negative value on failure.

THROWS:

IllegalMonitorStateException: if the current thread doesnot own the monitor.


NIO Support


The NIO-related entry points allow native code to accessjava.niodirect buffers. The contents of a directbuffer can, potentially, reside in native memory outside of the ordinarygarbage-collected heap. For information about direct buffers, please seebuffersin the NIO package and the specification of thejava.nio.ByteBufferclass.

Three functions allow JNI code to create, examine, and manipulatedirect buffers:

Every implementation of the Java virtual machine must support thesefunctions, but not every implementation is required to support JNIaccess to direct buffers. If a JVM does not support such access then theNewDirectByteBuffer andGetDirectBufferAddressfunctions must always returnNULL, and theGetDirectBufferCapacity function must always return-1. If a JVMdoes support such access then thesethree functions must be implemented to return the appropriatevalues.


NewDirectByteBuffer

jobject NewDirectByteBuffer(JNIEnv* env, void* address, jlong capacity);

Allocates and returns a directjava.nio.ByteBufferreferring to the block of memory starting at the memory addressaddress and extendingcapacity bytes. The byteorder of the returned buffer is always big-endian (high byte first;java.nio.ByteOrder.BIG_ENDIAN).

Native code that calls this function and returns the resultingbyte-buffer object to Java-level code should ensure that the bufferrefers to a valid region of memory that is accessible for reading and,if appropriate, writing. An attempt to access an invalid memory locationfrom Java code will either return an arbitrary value, have no visibleeffect, or cause an unspecified exception to be thrown.

LINKAGE:

Index 229 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

address: the starting address of the memory region, mustnot beNULL.

capacity: the size in bytes of the memory region, mustbe nonnegative and less than or equal toInteger.MAX_VALUE

RETURNS:

Returns a local reference to the newly-instantiatedjava.nio.ByteBuffer object. ReturnsNULL if anexception occurs, or if JNI access to direct buffers is not supported bythis virtual machine.

THROWS:

IllegalArgumentException: ifcapacity isnegative or greater thanInteger.MAX_VALUE

OutOfMemoryError: if allocation of theByteBuffer object fails

SINCE:

JDK/JRE 1.4


GetDirectBufferAddress

void* GetDirectBufferAddress(JNIEnv* env, jobject buf);

Fetches and returns the starting address of the memory regionreferenced by the given directjava.nio.Buffer.

This function allows native code to access the same memory regionthat is accessible to Java code via the buffer object.

LINKAGE:

Index 230 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

buf: a directjava.nio.Buffer object, mustnot beNULL.

RETURNS:

Returns the starting address of the memory region referenced by thebuffer. ReturnsNULL if the memory region is undefined, ifthe given object is not a directjava.nio.Buffer, or if JNIaccess to direct buffers is not supported by this virtual machine.

SINCE:

JDK/JRE 1.4


GetDirectBufferCapacity

jlong GetDirectBufferCapacity(JNIEnv* env, jobject buf);

Fetches and returns the capacity of the memory region referenced bythe given directjava.nio.Buffer. The capacity is thenumber ofelements that the memory region contains.

LINKAGE:

Index 231 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

buf: a directjava.nio.Buffer object, mustnot beNULL.

RETURNS:

Returns the capacity of the memory region associated with the buffer.Returns-1 if the given object is not a directjava.nio.Buffer, if the object is an unaligned view bufferand the processor architecture does not support unaligned access, or ifJNI access to direct buffers is not supported by this virtualmachine.

SINCE:

JDK/JRE 1.4


Reflection Support

Programmers can use the JNI to call Java methods or access Javafields if they know the name and type of the methods or fields. The JavaCore Reflection API allows programmers to introspect Java classes atruntime. JNI provides a set of conversion functions between field andmethod IDs used in the JNI to field and method objects used in the JavaCore Reflection API.


FromReflectedMethod

jmethodID FromReflectedMethod(JNIEnv *env, jobject method);

Converts ajava.lang.reflect.Method orjava.lang.reflect.Constructor object to a method ID.

LINKAGE:

Index 7 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

method: ajava.lang.reflect.Method orjava.lang.reflect.Constructor object, must not beNULL.

RETURNS:

A JNI method ID that corresponds to the given Java reflection method,or NULL if the operation fails.

SINCE:

JDK/JRE 1.2


FromReflectedField

jfieldID FromReflectedField(JNIEnv *env, jobject field);

Converts ajava.lang.reflect.Field to a field ID.

LINKAGE:

Index 8 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

field: ajava.lang.reflect.Field object,must not beNULL.

RETURNS:

A JNI field ID that corresponds to the given Java reflectionfield, orNULL if the operation fails.

SINCE:

JDK/JRE 1.2


ToReflectedMethod

jobject ToReflectedMethod(JNIEnv *env, jclass cls, jmethodID methodID, jboolean isStatic);

Converts a method ID derived fromcls to ajava.lang.reflect.Method orjava.lang.reflect.Constructor object.isStaticmust be set toJNI_TRUE if the method ID refers to a staticfield, andJNI_FALSE otherwise.

ThrowsOutOfMemoryError and returns 0 if fails.

LINKAGE:

Index 9 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

cls: a Java class object, must not beNULL.

methodID: a method ID, must not beNULL.

isStatic: denotes whether the givenmethodID is a static method.

RETURNS:

Returns an instance of thejava.lang.reflect.Method orjava.lang.reflect.Constructor which corresponds to thegivenmethodID, orNULL if the operationfails.

SINCE:

JDK/JRE 1.2


ToReflectedField

jobject ToReflectedField(JNIEnv *env, jclass cls, jfieldID fieldID, jboolean isStatic);

Converts a field ID derived fromcls to ajava.lang.reflect.Field object.isStatic mustbe set toJNI_TRUE iffieldID refers to astatic field, andJNI_FALSE otherwise.

ThrowsOutOfMemoryError and returns 0 if fails.

LINKAGE:

Index 12 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

cls: a Java class object, must not beNULL.

fieldID: a field ID, must not beNULL.

isStatic: denotes whether the givenfieldIDis a static field.

RETURNS:

Returns an instance of thejava.lang.reflect.Field whichcorresponds to the givenfieldID, orNULL ifthe operation fails.

SINCE:

JDK/JRE 1.2


Java VM Interface


GetJavaVM

jint GetJavaVM(JNIEnv *env, JavaVM **vm);

Returns the Java VM interface (used in the Invocation API) associatedwith the current thread. The result is placed at the location pointed toby the second argument,vm.

LINKAGE:

Index 219 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer, must not beNULL.

vm: a pointer to where the result should be placed, mustnot beNULL.

RETURNS:

Returns "0" on success; returns a negative value on failure.


[8]ページ先頭

©2009-2025 Movatter.jp