C12Adapter Opensource C++ Interface
MJavaEnv Class Reference

Scoped Java environment handler. More...

Public Types

enum  { JniVersion = JNI_VERSION_1_4 }
 

Public Member Functions

 MJavaEnv ()
 Most useful constructor that fetches the environment and stores it internally for further use. More...
 
 MJavaEnv (JNIEnv *env)
 Constructor that takes an explicit environment. More...
 
 ~MJavaEnv ()
 Destructor that unregisters the java environment. More...
 
void AddToLocalObjects (jobject obj)
 Add a given Java object to the list of local objects that have to be deleted at destruction. More...
 
jbyteArray NewLocalByteArray (int size)
 Create a new uninitialized Java byte array and add it to the list of local references. More...
 
jbyteArray NewLocalByteArray (const char *buff, int size)
 Create a new initialized Java byte array and add it to the list of local references. More...
 
void ExceptionCppToJava (MException &ex)
 Object method that initializes the java exception in the current environment from a given C++ exception. More...
 
void CheckForJavaException ()
 Convert java exception, if it is present, into C++. More...
 
jclass FindClass (const char *javaClassName)
 Find Java class, throw error if it is not found. More...
 
jmethodID GetMethodID (jclass clazz, const char *name, const char *signature)
 Get Java method ID, throw error if it is not found. More...
 
jmethodID GetStaticMethodID (jclass clazz, const char *name, const char *signature)
 Get Java static method ID, throw error if it is not found. More...
 
jfieldID GetFieldID (jclass clazz, const char *name, const char *signature)
 Get Java field ID, throw error if it is not found. More...
 
jfieldID GetStaticFieldID (jclass clazz, const char *name, const char *signature)
 Get Java static field ID, throw error if it is not found. More...
 
JNIEnv * GetEnv ()
 
const JNIEnv * GetEnv () const
 
JNIEnv * operator-> ()
 
const JNIEnv * operator-> () const
 
jstring NewLocalStringUTF (const char *str)
 
jstring NewLocalStringUTF (const MStdString &str)
 

Static Public Member Functions

static void StaticExceptionCppToJava (JNIEnv *jenv, MException &ex)
 Class method that initializes java exception in the current environment from a given C++ exception. More...
 
static void CheckForJniError (jint code, const char *errorMessage)
 Check for JNI error code. More...
 

Detailed Description

Scoped Java environment handler.

Use this class as a wrapper of methods that call Java code from C++ as it provides java environment variable for the current thread context. Typical, most generic and reliable example of full use of the class:

void MyCppClass::MyCppClass() // constructor
{
MJavaEnv env;
jclass c = env.FindClass("org/me/MyJavaClass"); // throws an exception at failure
jmethodID idConstructor = env.GetMethodID(c, "<init>", "()V");
jobject o = env->NewObject(c, idConstructor, portNameJ);
env.CheckForJavaException(); // the above c and o were local objects, they need not be destroyed
// if the exception is raised
// Globalize local references and store them in class.
// Storing the class reference is optional as all method IDs
// can be resolved here in the constructor.
m_javaClass = static_cast<jclass>(env->NewGlobalRef(c));
m_javaObject = env->NewGlobalRef(o);
}
void MyCppClass::~MyCppClass() // destructor
{
MJavaEnv env;
// If we do not have to call anything in Java at destruction, just delete references
env->DeleteGlobalRef(m_javaObject); // free pointer, mark for garbage collector
env->DeleteGlobalRef(m_javaClass); // (only if a global reference is stored)
}
void MyCppClass::MyCppMethodThatCallsJavaMethods()
{
MJavaEnv env;
// If method ID was not already fetched somewhere
jmethodId methodId = env.GetMethodID(m_javaClass, "someJavaMethod", "()V");
env->CallVoidMethod(m_javaObject, methodId);
}

As a slight optimization it is possible to reuse java environment class among several calls, however one has to be careful as java environment has to be created and released within a context of a single Java call, or a single detached C++ thread.

Member Enumeration Documentation

anonymous enum
Enumerator
JniVersion 

JNI version used by the interface.

Constructor & Destructor Documentation

MJavaEnv::MJavaEnv ( )

Most useful constructor that fetches the environment and stores it internally for further use.

The class has to be created in C++ code that is by itself working within Java. If necessary, and the current C++ thread is not registered with Java, the registering is performed.

MJavaEnv::MJavaEnv ( JNIEnv *  env)

Constructor that takes an explicit environment.

This has to be called within the registered Java thread when the environment is received already. It is assumed that the java environment is already registered with java thread.

Parameters
envJava environment to be used within the object.
MJavaEnv::~MJavaEnv ( )

Destructor that unregisters the java environment.

If the environment was executed in a context of a C++ only thread it is unregistered.

Member Function Documentation

void MJavaEnv::AddToLocalObjects ( jobject  obj)

Add a given Java object to the list of local objects that have to be deleted at destruction.

This method is a handy way of dealing with JNI local references that have to be removed at the exit of method.

void MJavaEnv::CheckForJavaException ( )

Convert java exception, if it is present, into C++.

This call should be made after any method such as JNI Call*Method that can raise Java exceptions. If a Java exception takes place, it is converted into a C++ exception of the most appropriate MeteringSDK exception class and thrown as C++ exception into C++. Any non-MeteringSDK exceptions will be converted into MException.

In between Call*Method and CheckForJavaException only very few JNI methods can be called:

ExceptionOccurred()
ExceptionDescribe()
ExceptionClear()
ExceptionCheck()
ReleaseStringChars()
ReleaseStringUTFChars()
ReleaseStringCritical()
Release<Type>ArrayElements()
ReleasePrimitiveArrayCritical()
DeleteLocalRef()
DeleteGlobalRef()
DeleteWeakGlobalRef()
MonitorExit()
PushLocalFrame()
PopLocalFrame()

as specified at http://docs.oracle.com/javase/8/docs/technotes/guides/jni/spec/design.html#exception_handling

static void MJavaEnv::CheckForJniError ( jint  code,
const char *  errorMessage 
)
static

Check for JNI error code.

Throw a C++ exception if the given result of JNI function is erroneous, not equal to JNI_OK.

Parameters
codeResult of a JNI function such as AttachCurrentThread or GetEnv.
errorMessageWhatever will be the error message if code is not JNI_OK. This string should not have C format parameters.
void MJavaEnv::ExceptionCppToJava ( MException ex)
inline

Object method that initializes the java exception in the current environment from a given C++ exception.

The robustness of this method assumes the presence of MTools Java facade that provides the exception hierarchy that matches the one of MeteringSDK. After the call is made, the execution should immediately reach Java code for the exception to be raised from there.

Parameters
exC++ exception that has to be converted into java exception of the current environment.
See also
StaticExceptionCppToJava - static version that is more convenient for cases when the native JNIEnv is already present.
CheckForJavaException - reverse method, convert java exception, if it is present, into C++.
jclass MJavaEnv::FindClass ( const char *  javaClassName)

Find Java class, throw error if it is not found.

Different from JNI FindClass, still available as

jclass c = env->FindClass("org/me/MyJavaClass");

this object method, callable with a period like this:

jclass c = env.FindClass("org/me/MyJavaClass");

will throw an exception if there is no such class.

Parameters
javaClassNameJava class name signature as specified by Java.
Returns
JNI class object.
JNIEnv* MJavaEnv::GetEnv ( )
inline

Access the native java environment.

This call is rarely necessary.

See also
operator->()
const JNIEnv* MJavaEnv::GetEnv ( ) const
inline

Access the native java environment.

This call is rarely necessary.

See also
operator->()
jfieldID MJavaEnv::GetFieldID ( jclass  clazz,
const char *  name,
const char *  signature 
)

Get Java field ID, throw error if it is not found.

Different from JNI GetFieldID, still available as

jclass c = env->GetFieldID(clazz, "fieldName", "I");

this object method, callable with a period like this:

jclass c = env.GetFieldID(clazz, "fieldName", "I");

will throw an exception if there is no such field.

Parameters
clazzJava class object.
nameField name.
signatureField signature, as defined by Java.
Returns
JNI field ID, not a null.
See also
GetStaticMethodID - for getting an ID of a class method.
jmethodID MJavaEnv::GetMethodID ( jclass  clazz,
const char *  name,
const char *  signature 
)

Get Java method ID, throw error if it is not found.

Different from JNI GetMethodID, still available as

jclass c = env->GetMethodID(clazz, "methodName", "()V");

this object method, callable with a period like this:

jclass c = env.GetMethodID(clazz, "methodName", "()V");

will throw an exception if there is no such method.

Parameters
clazzJava class object.
nameMethod name.
signatureMethod signature, as defined by Java.
Returns
JNI method ID, not a null.
See also
GetStaticMethodID - for getting an ID of a class method.
jfieldID MJavaEnv::GetStaticFieldID ( jclass  clazz,
const char *  name,
const char *  signature 
)

Get Java static field ID, throw error if it is not found.

Different from JNI GetStaticFieldID, still available as

jclass c = env->GetStaticFieldID(clazz, "fieldName", "I");

this object method, callable with a period like this:

jclass c = env.GetStaticFieldID(clazz, "fieldName", "I");

will throw an exception if there is no such static field.

Parameters
clazzJava class object.
nameField name.
signatureField signature, as defined by Java.
Returns
JNI field ID, not a null.
See also
GetStaticMethodID - for getting an ID of a class method.
jmethodID MJavaEnv::GetStaticMethodID ( jclass  clazz,
const char *  name,
const char *  signature 
)

Get Java static method ID, throw error if it is not found.

Different from JNI GetStaticMethodID, still available as

jclass c = env->GetStaticMethodID(clazz, "methodName", "()V");

this object method, callable with a period like this:

jclass c = env.GetStaticMethodID(clazz, "methodName", "()V");

will throw an exception if there is no such method.

Parameters
clazzJava class object.
nameMethod name.
signatureMethod signature, as defined by Java.
Returns
JNI method ID, not a null.
See also
GetMethodID - for getting an ID of an object method.
jbyteArray MJavaEnv::NewLocalByteArray ( int  size)

Create a new uninitialized Java byte array and add it to the list of local references.

Parameters
sizeSize of the array.
Returns
Java byte array object.
jbyteArray MJavaEnv::NewLocalByteArray ( const char *  buff,
int  size 
)

Create a new initialized Java byte array and add it to the list of local references.

Parameters
buffBuffer with byte values.
sizeSize of the buffer and the result byte array.
Returns
Java byte array object.
jstring MJavaEnv::NewLocalStringUTF ( const char *  str)

Create a new Java string from UTF string and add it to the list of local references.

Parameters
strString in UTF encoding from which a Java string has to be created.
Returns
Java string object.
jstring MJavaEnv::NewLocalStringUTF ( const MStdString str)
inline

Create a new Java string from UTF string and add it to the list of local references.

Parameters
strString in UTF encoding from which a Java string has to be created.
Returns
Java string object.
JNIEnv* MJavaEnv::operator-> ( )
inline

Call JNI methods using this environment class.

This operator saves a call of GetEnv() so that instead of

jmethodID idRead = env.GetEnv()->GetMethodID(clazz, "read", "([BII)I");

one has:

jmethodID idRead = env->GetMethodID(clazz, "read", "([BII)I");

Notice, MJavaEnv provides a number of wrapper methods that in addition to natives verifies the result of the operation and throws an exception at failure. For example, notice '.' instead of '->'

jmethodID idRead = env.GetMethodID(clazz, "read", "([BII)I"); // throws if such method is not found
Returns
Native java environment variable.
const JNIEnv* MJavaEnv::operator-> ( ) const
inline

Call JNI methods using this environment class.

This operator saves a call of GetEnv() so that instead of

jmethodID idRead = env.GetEnv()->GetMethodID(clazz, "read", "([BII)I");

one has:

jmethodID idRead = env->GetMethodID(clazz, "read", "([BII)I");

Notice, MJavaEnv provides a number of wrapper methods that in addition to natives verifies the result of the operation and throws an exception at failure. For example, notice '.' instead of '->'

jmethodID idRead = env.GetMethodID(clazz, "read", "([BII)I"); // throws if such method is not found
Returns
Native java environment variable.
static void MJavaEnv::StaticExceptionCppToJava ( JNIEnv *  jenv,
MException ex 
)
static

Class method that initializes java exception in the current environment from a given C++ exception.

The robustness of this method assumes the presence of MTools Java facade that provides the exception hierarchy that matches the one of MeteringSDK. After the call is made the execution should immediately reach Java code for the exception to be raised from there.

Parameters
jenvNative Java environment.
exC++ exception that has to be converted into java exception for the current environment.
See also
ExceptionCppToJava - non-static version that is more convenient when there is MJavaEnv present.
CheckForJavaException - reverse method, convert java exception, if it is present, into C++.