Professional Documents
Culture Documents
Method)
Lecture 9
static {
System.loadLibrary("CBookM");
}
env->Call<Type>Method(obj, mid);
It calls the specific
instance method from Java
env->CallVoidMethod(obj, mid); class
GetVoidMethod because return type of setStatus() and showStatus() are void data type.
Calling Instance Method (Example 2)
Java source code: BookP.java
class BookP{
private boolean status;
private native void read();
private static void check(double x){ Call the check method by passing value of 25.99 as input parameter
System.out.println("Price of the book = RM" + x);
}
static {
System.loadLibrary("CBookH");
}
public static void main (String args[]){
BookH c = new BookH();
c.read();
}
}
Calling Static Method (Example 1)
Compilation Process of JNI
class reference
env->CallStatic<Type>Method(cls, mid);
It calls the specific static
method from Java class.
env->CallStaticVoidMethod(cls, mid);
value for a
CallStatic<Type>Method Function
Return Type CallStatic<Type>Method
void CallStaticVoidMethod()
jboolean CallStaticBooleanMethod()
jbyte CallStaticByteMethod()
jchar CallStaticCharMethod()
Primitive type jshort CallStaticShortMethod()
jint CallStaticIntMethod()
jlong CallStaticLongMethod()
jfloat CallStaticFloatMethod()
jdouble CallStaticDoubleMethod()
jobject CallStaticObjectMethod()
Class type jstring CallStaticObjectMethod()
Calling Static Method (Example 2)
Java source code: BookS.java C++ native code: CBookS.cpp
field/method declaration: input parameters:
static method: int multiple(int x) interface pointer: env
native method: void read( ) object reference: obj
private static int multiple (int x){ jint result = env -> CallStaticIntMethod(cls, mid, 8); //call multiple()
return x*x; cout<<"This result is "<< result;
} }
passing the value of 8 as input parameter
static {
System.loadLibrary("CBookS");
}
public static void main (String args[]){
BookS c = new BookS();
c.read();
}
}
Calling Static Method (Example 2)
Compilation Process of JNI
// Step 2: compile Java source code
class Q5{
public native void printLength(String name);
static {
System.loadLibrary("CQ5");
}
Q5 ww = new Q5();
ww.printLength(name);
}
}
Extra Exercise (Q1)
#include "Q5.h"
#include <iostream>
using namespace std;
env->ReleaseStringUTFChars(text, str);
return;
}
Extra Exercise (Q1)
Extra Exercise (Q2)
import java.util.Scanner;
class Q6 {
public native String printNum(int num);
static {
System.loadLibrary("CQ6");
}
Q6 ww = new Q6();
System.out.print("The result is " + ww.printNum(num));
}
}
Extra Exercise (Q2)
#include "Q6.h"
#include <cstring>
char temp[20];
jstring result;
if (nn%2 == 0)
strcpy(temp, "even number");
else
strcpy(temp, "odd number");
result = env->NewStringUTF(temp);
return result;
}
Extra Exercise (Q2)