unit test;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls,jni;
type
TForm1 = class(TForm)
Button1: TButton;
Edit1: TEdit;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
jvm: Jni.PJavaVM;
tenv: Jni.TJNIEnv;
cid: Jni.JClass;
mid: Jni.JMethodID;
tmp: Jni.JString;
sj:Jni.JString;
vm_args: Jni.JavaVMInitArgs; //建立 JVM 的參數
options: array[0..2] of Jni.JavaVMOption;
env: Jni.PJNIEnv;
rec: Integer;
jclsIns:JObject;
ret:String;
const
str='傳給java的參數是--' +'你好,java jni,我要战胜你!';
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
var
excep:Jni.JThrowable;
pjval:jni.PJValue;
begin
options[0].optionString := '-Djava.compiler=NONE';
options[1].optionString := '-Djava.class.path=D:\\insure_XT\\insurext\\build\\classes'; // Java 工程路徑, '.' 表示黨前路徑
options[2].optionString := '-verbose:jni';
JNI_GetDefaultJavaVMInitArgs(@vm_args);
vm_args.version := Jni.JNI_VERSION_1_6;
vm_args.options := @options;
vm_args.nOptions := 3;
vm_args.ignoreUnrecognized := Jni.JNI_TRUE;
rec := Jni.JNI_CreateJavaVM(@jvm, @env, @vm_args); //建立JVM
if (rec = JNI_ERR ) then begin
edit1.Text:='建立java虚拟机jvm出错(Jni.JNI_CreateJavaVM)';
exit;
end;
tenv := TJNIEnv.Create(env);
if tenv=nil then Begin
edit1.Text:='获取java环境出错';
Exit;
End;
//取得 DelphiCallJava 的類ID, 如果有'包',也指定, <package>.<class>
cid := tenv.FindClass('insure/Test');
if (tenv.ExceptionCheck()) then begin
edit1.Text:='找不到类insure.Test';
excep:=tenv.ExceptionOccurred;
tenv.ExceptionClear;
freeAndNil(tenv);
jvm^.DestroyJavaVM(jvm);
Exit;
end
else
begin
edit1.Text:='找到类insure/Test';
end;
//初始化类的新实例
mid:=tenv.GetMethodID(cid,'<init>','()V');
if(mid=nil) then begin
edit1.Text:='获取Test类的构造函数出错';
freeAndNil(tenv);
jvm^.DestroyJavaVM(jvm);
Exit;
end;
jclsIns:=tenv.NewObjectV(cid,mid,nil);
if(jclsIns=nil) then begin
edit1.Text:='初始化类出错';
freeAndNil(tenv);
jvm^.DestroyJavaVM(jvm);
Exit;
end;
//取得方法ID
mid := tenv.GetMethodID(cid, 'jniTest', '(Ljava/lang/String;)Ljava/lang/String;'); //(Ljava/lang/String;)I
if (mid = nil) then begin
edit1.Text:='找不到方法jniTest';
freeAndNil(tenv);
jvm^.DestroyJavaVM(jvm);
Exit;
end
else
edit1.Text:='找到jniTest方法';
//將 string 轉換成 java string
tmp := tenv.StringToJString(PChar(UTF8Encode(str)));
//用類ID和方法ID調用 JAVA 方法
//pjval:=tenv.ArgsToJValues([tmp]);
sj:=tenv.CallObjectMethod(jclsIns, mid,[tmp]);
//sj:=env^.CallIntMethodV(env,cid,mid,nil);
//ret:=tenv.JStringToString(sj);
ret:=tenv.UnicodeJStringToString(sj);
self.Canvas.TextOut(40,40, str);
self.canvas.textout(60,60,'返回值为--' + ret);
edit1.Text:='从java类获取的方法结果为';
if tenv<>nil then begin
freeAndNil(tenv);
jvm^.DestroyJavaVM(jvm); //釋放JVM資源
End;
end;
end.