-
-
-
- package jni;
-
- import java.util.Iterator;
- import java.util.List;
-
-
-
-
-
- public class StuService {
-
- static {
- System.loadLibrary("student");
- }
-
-
-
-
-
- public static native List getStuList();
-
-
-
-
-
-
- public native Student getStudent();
-
-
- public static void main(String[] args) {
- StuService stuService=new StuService();
- stuService.getStudent().toString();
-
- List list=StuService.getStuList();
- for(Iterator ite=list.iterator();ite.hasNext();)
- {
- Student stu=(Student)ite.next();
- stu.toString();
- }
-
-
- }
-
- }
声明native方法:如果你想将一个方法做为一个本地方法的话,那么你就必须声明改方法为native的,并且不能实现。
Load动态库:System.loadLibrary("student");
1.2 编译StuService.java
javac -classpath . -d . jni/StuService.java
2.生成jni_StuService.h头文件
javah -classpath . -d . jni.StuService
cpp 代码(jni_StuService.h)
-
- #include "jni.h"
-
-
- #ifndef _Included_jni_StuService
- #define _Included_jni_StuService
- #ifdef __cplusplus
- extern "C" {
- #endif
-
-
-
-
-
- JNIEXPORT jobject JNICALL Java_jni_StuService_getStuList
- (JNIEnv *, jclass);
-
-
-
-
-
-
- JNIEXPORT jobject JNICALL Java_jni_StuService_getStudent
- (JNIEnv *, jobject);
-
-
-
-
-
-
- jobject constructStudent(JNIEnv *env ,int i);
-
- #ifdef __cplusplus
- }
- #endif
- #endif
3.在VC++环境中创建一个动态链接库的项目
3.1 File->new->Projects->Win32 Dynamic-Link Library
3.2 将jni_StuService.h加入Header Files
3.3 %root%\j2sdk1.4.2_10\include\jni.h 和%root%\j2sdk1.4.2_10\include\win32\jni_md.h加入Header Files
3.4 创建student.cpp,并实现 jni_StuService.h中的Java_jni_StuService_getStudent和Java_jni_StuService_getStuList的方法.
cpp 代码(student.cpp)
- #include "jni_StuService.h"
-
-
-
-
-
- jobject JNICALL Java_jni_StuService_getStuList
- (JNIEnv *env, jclass)
- {
-
-
- jclass class_ArrayList=env->FindClass("java/util/ArrayList");
-
- jmethodID construct=env->GetMethodID( class_ArrayList, "<init></init>","()V");
-
- jobject obj_List =env->NewObject( class_ArrayList, construct, "");
-
-
-
-
-