原文:http://www.cnblogs.com/crazywolf/archive/2011/07/21/2112276.html
学习JAVA已经有段时间,其中非常重要的一环是将原有的C代码用JNI的方式让JAVA去调用。今天解决了一个对enum类型处理的问题。
原理很简单,enum 其实也是一个类,那这个类有什么特色呢?
例如我定义了一个类:
2 public enum Parity {
3 None( 0 ),
4 Odd( 1 ),
5 Even( 2 ),
6 Mark( 3 ),
7 Space( 4 );
8 private int value;
9 private Parity( int value) {
10 this .value = value;
11 }
12 public int value() {
13 return this .value;
14 }
15 }
16
17 public native boolean setParity(Parity parity);
18 public native Parity getParity();
19 }
那么使用 javap -s SerialPort.Parity 可得到:
Compiled from "SerialPort.java"
public final class SerialPort$Parity extends java.lang.Enum {
public static final SerialPort$Parity None;
Signature: LSerialPort$Parity;
public static final SerialPort$Parity Odd;
Signature: LSerialPort$Parity;public static final SerialPort$Parity Even;
Signature: LSerialPort$Parity;public static final SerialPort$Parity Mark;
Signature: LSerialPort$Parity;public static final SerialPort$Parity Space;
Signature: LSerialPort$Parity;
Signature: ()V
public int value();
Signature: ()I
public static SerialPort$Parity[] values();
Signatue: ()[LSerialPort$Parity;
public static SerialPort$Parity valueOf(java.lang.String);
Signature: (Ljava/lang/String;)LSerialPort$Parity;
}
看到这里的信息就明朗了,Enum类就是包含多个定义的Enum类本身的静态常量,加上一些自定义的方法。那想要操作它就像操作一般的类一样了。在C代码里可以这样操作即可达到使用Enum类。
jclass clsParity = ( * env) -> GetObjectClass(env, parity);
jmethodID idValue = ( * env) -> GetMethodID(env, clsParity, " value " , " ()I " );
gint32 value = ( * env) -> CallIntMethod(env, parity, idValue);
if (serial_port_set_parity(get_port_address(env, obj), (XDSerialPortParity)value))
return JNI_TRUE;
return JNI_FALSE;
}
jobject Java_SerialPort_getParity(JNIEnv * env, jobject obj) {
jclass clrParity = ( * env) -> FindClass(env, " SerialPort$Parity " );
jfieldID id = NULL;
switch (serial_port_get_parity(get_port_address(env, obj))) {
case SERIAL_PORT_PARITY_NONE:
id = ( * env) -> GetStaticFieldID(env, clrParity, " None " , " LSerialPort$Parity; " );
break ;
case SERIAL_PORT_PARITY_ODD:
id = ( * env) -> GetStaticFieldID(env, clrParity, " Odd " , " LSerialPort$Parity; " );
break ;
case SERIAL_PORT_PARITY_EVEN:
id = ( * env) -> GetStaticFieldID(env, clrParity, " Even " , " LSerialPort$Parity; " );
break ;
case SERIAL_PORT_PARITY_MARK:
id = ( * env) -> GetStaticFieldID(env, clrParity, " Mark " , " LSerialPort$Parity; " );
break ;
case SERIAL_PORT_PARITY_SPACE:
id = ( * env) -> GetStaticFieldID(env, clrParity, " Space " , " LSerialPort$Parity; " );
break ;
}
return ( * env) -> GetStaticObjectField(env, clrParity, id);
}