转载地址:http://topic.csdn.net/t/20040812/18/3268919.html
有个问题是为什么例如"FileOutputStream"这些类里并没有以下的调用?
static {
System.loadLibrary("NativeDemo");
}
以下是一个例子: // A simple example that uses a native method. public class NativeDemo { int i; public static void main(String args[]) { NativeDemo ob = new NativeDemo(); ob.i = 10; System.out.println("This is ob.i before the native method:" + ob.i); ob.test(); // call a native method System.out.println("This is ob.i after the native method:" + ob.i); } // declare native method public native void test() ; // load DLL that contains static method static { System.loadLibrary("NativeDemo"); } } 注意test( )方法声明为native且不含方法体。简而言之这是我们用C语言实现的方法。 写完程序后,编译它生成NativeDemo.class。然后,你必须用javah.exe生成一个文件: NativeDemo.h(javah.exe包含在JDK中)。在执行test( )时你要包含NativeDemo.h。为生成 NativeDemo.h,用下面的命令: javah -jni NativeDemo 该命令生成名为NativeDemo.h的头文件。该文件必须包含在实现test()的C文件中。该命 令的输出结果如下: /* DO NOT EDIT THIS FILE - it is machine generated */ #include /* Header for class NativeDemo */ #ifndef _Included_NativeDemo #define _Included_NativeDemo #ifdef _ _cplusplus extern "C" { #endif /* * Class: NativeDemo * Method: test * Signature: ()V */ JNIEXPORT void JNICALL Java_NativeDemo_test (JNIEnv *, jobject); #ifdef _ _cplusplus } #endif #endif 注意函数的名称是Java_NativeDemo_test( )。调用本机函数你必须用这样的名字。也就 是说,不是生成一个名为test( )的C函数,而是创建一个名为Java_NativeDemo_test( )函数。 生成了必备的头文件后,可以编写test( )执行文件并把它存在一个名为NativeDemo.c的 文件中: /* This file contains the C version of the test() method. */ #include #include "NativeDemo.h" #include JNIEXPORT void JNICALL Java_NativeDemo_test(JNIEnv *env, jobject obj) { jclass cls; jfieldID fid; jint i; printf("Starting the native method./n"); cls = (*env)->GetObjectClass(env, obj); fid = (*env)->GetFieldID(env, cls, "i", "I"); if(fid == 0) { printf("Could not get field id./n"); return; } i = (*env)->GetIntField(env, obj, fid); printf("i = %d/n", i); (*env)->SetIntField(env, obj, fid, 2*i); printf("Ending the native method./n"); } 注意此文件包含具有接口信息的jni.h文件。该文件由你的Java 编译器提供。头文件 NativeDemo.h预先已由javah创建。 该函数中,GetObjectClass( )方法用来获得一个含有NativeDemo类信息的C结构。 GetFieldID( )方法返回一个包含该类域名“i”信息的C结构。GetIntField()检索该域原来的 值。SetIntField( )存储该域的一个更新值(别的处理其他数据类型的方法参看文件jni.h)。 生成NativeDemo.c文件后,必须编译它生成一个DLL文件。用微软C/C++编译器来做, 使用下面的命令行: Cl /LD NativeDemo.c 它生成了一个名为NativeDemo.dll的文件。该步骤完成,你可以执行Java 程序。该程序输出如下: This is ob.i before the native method: 10 Starting the native method. i = 10 Ending the native method. This is ob.i after the native method: 20 以上摘自《JAVA 参考大全》