【发布时间】:2014-02-26 02:02:12
【问题描述】:
对于我的一个项目,我正在使用 Java 本机接口 (JNI)。
我的项目包含一个 JNI 系统,它使用端口参数在 de C++ 端调用一个函数。此函数返回一个 Object 数组,如下面的 cmets 中所写,问题在最后一条评论中说明:
public Integer SpawnNewConnectionHandler(Integer Port) throws WrapperException {
//Creation of the object array that will hold the result
Object[] result;
//Get the result object array from the external library. Length of the array is either 1 or 2.
//While debugging i found out that it contains two elements of the type int (Not integer, but its basetype).
//This means that nothing on the c++ side went wrong.
result = spawnNewServerConnectionHandler(Port);
//Error coming from the SDK should be handled here. (Code snipped as the if clause checking for it, is not being called.)
//The snipped will throw a WrapperException if the length of the array returned is not 1.
//The debugger will break here and show me that before executing this line both of the result objects are not empty,
//So result[0] and result[1] are filled with data, for result[1] it is a 1 or higher. For result[0] is is the number 0. (Returned as a fact that everything went alright while executing.)
//During execution of this line the program crashes and shows a NullPointerException.
//
//I found out that it is impossible for it to cast the object, stored in the object array as a int into a Integer.
//Doing this manually while debugging shows the following error message:
//"Unable to cast numeric value to java.lang.Integer."
return (Integer) result[1];
}
有没有人知道这个问题的解决方案,或者至少为什么它会给我这个奇怪的错误?
【问题讨论】:
-
您是否尝试过将
Object[] result声明为int[] result?我怀疑你有一个原始数组,在这种情况下你的返回看起来像Integer.valueOf(result[1])。 -
sigpwned,我确实有一个包含由外部库返回的整数的 ObjectArray。如果我尝试强制转换,则会在编译时给我一个错误,并且它说这两种类型不兼容。
-
int[]和Integer[]数组之间存在差异。即,第一个是原始类型,第二个是对象类型。根据您在下面对{int[2]@2559}的评论,很明显您手上有一个原始数组。稍等一下——我会用一些我认为有用的代码来回应。 -
是的,我知道,但是转换无法正常工作,编译器抛出一个错误,抱怨不兼容的类型,期待 int[] found java.lang.object[]。
标签: java nullpointerexception java-native-interface integer int