Android 2.2 中反射未完全实现?
我有一些代码在 2.3 及更高版本中运行良好。然而,在 2.2 中,当 className 被分配时,我得到一个 NullPointerException:
if(field.getType() == java.util.ArrayList.class)
className = ((ParameterizedType)field.getGenericType()).toString();
编辑
我在 android 文档上进行了一些窥探,发现某些方法直到 API 级别 9 才可用。但是, getType( )、getGenericType() 和 ParameterizedType 据说都在 API 级别 1 上受支持。那么为什么这段代码不起作用呢?
字段文档: http://developer.android.com/reference/java/ lang/reflect/Field.html
ParameterizedType 文档:http://developer.android.com/reference/java/lang/reflect/ParameterizedType.html
编辑
我发现调用 field.getGenericType() 确实不会导致程序崩溃,而是默默地抛出 com.sun.jdi.InitationException。调用 getGenericType() 返回的 Type 似乎无效?同样,这适用于 2.3 及更高版本,但为什么在 2.2 及更低版本上会抛出并捕获此异常?
I have some code that runs fine in 2.3 and above. However, in 2.2 I get an NullPointerException when className is getting assigned:
if(field.getType() == java.util.ArrayList.class)
className = ((ParameterizedType)field.getGenericType()).toString();
EDIT
I did some snooping around on the android docs and found that some of the methods are not available until API level 9. However, getType(), getGenericType(), and ParameterizedType are all said to be supported at API level 1. So why doesn't this code work?
Field docs: http://developer.android.com/reference/java/lang/reflect/Field.html
ParameterizedType docs: http://developer.android.com/reference/java/lang/reflect/ParameterizedType.html
EDIT
I found out that calling field.getGenericType() does not cause the program to crash, but silently throws a com.sun.jdi.InvocationException. It seems like the Type returned from the call to getGenericType() is not valid? Again, this works on 2.3 and above, but why is this exception being thrown and caught on 2.2 and below?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一个已知问题,以下是 Android 错误跟踪器中的票证:问题 6636:组织中的 NPE .apache.harmony.luni.lang.reflect.ListOfTypes
它已在 Android 2.3 中修复,但尚未向后移植到早期 Android 版本,这就是您在 Android 2.2 中看到崩溃的原因。
更详细地说:如果您在 Android 2.2 上运行此代码(您自己的代码的扩展版本):
您将得到此异常:
因为 Java 反射实现中存在上述错误。在 Android 2.3 上,该错误已得到修复,您将在 logcat 中看到以下内容:
据我所知,您所看到的 com.sun.jdi.InvocableException 异常与此无关。
This is a known issue, here is the ticket in the Android bug tracker: Issue 6636: NPE in org.apache.harmony.luni.lang.reflect.ListOfTypes
It was fixed in Android 2.3 but has not been backported to earlier Android releases which is why you see the crash in Android 2.2.
To be more elaborate: if you run this code (an extended version of your own code) on Android 2.2 :
You will get this exception:
because of the above mentioned bug in the Java reflection implementation. On Android 2.3, the bug has been fixed, and you'll see this in the logcat instead:
The
com.sun.jdi.InvocationException
exception your are seeing is unrelated to this as far as I can tell.