JNI中抛出异常

来源:互联网 发布:江汉大学网络课程入口 编辑:程序博客网 时间:2024/04/29 05:13

From: http://blog.csdn.net/sunnydogzhou/article/details/5564492

应用场景:

利用Java的JNI机制调用C写好的类库,现在需要在C的类库中抛出异常,然后在应用层即java上面捕获异常。

 

具体的实现形式如下

首先定义一个异常类


class NumberNotFounded extends Exception {
    NumberNotFounded(){
        super();
    }   
    NumberNotFounded(String reason){
        super(reason);   
    }
}

 

接着定义一个带有native方法的JNI类。

class ExceptionAccess{

    public native int doit();

    static {
        System.load("/home/dianping/Peter/Exception/libExceptionAccess.so");   
    }   
}

 

我们会在doit()中抛出异常。先用javah生成头文件

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class ExceptionAccess */

#ifndef _Included_ExceptionAccess
#define _Included_ExceptionAccess
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     ExceptionAccess
 * Method:    doit
 * Signature: ()I
 */
JNIEXPORT jint JNICALL Java_ExceptionAccess_doit
  (JNIEnv *, jobject);

#ifdef __cplusplus
}
#endif
#endif


接着编写.c文件

 

#include "ExceptionAccess.h"

JNIEXPORT jint JNICALL Java_ExceptionAccess_doit
  (JNIEnv * env, jobject obj)
{
    jclass cls;
    cls = ( *env)->FindClass(env,"NumberNotFounded");
    if(cls == NULL){
        return;
    }   
    (*env)->ThrowNew(env,cls,"code from C");
}

编译之,记得编译的时候用 -I带上头文件的路径,不知道可以baidu之。

 

然后编写一个测试的类

 

import java.io.*;

class caller {
    public static void main(String args[]) {
        ExceptionAccess EA = new ExceptionAccess();
        try
        {
            EA.doit();

        }catch (Exception e){
            System.out.println("java c"+e);
        }
    }
}

 

到此完成


0 0
原创粉丝点击