why a Socket is not instanceof Closeable at runtime?

匿名 (未验证) 提交于 2019-12-03 02:03:01

问题:

In an Android app, I added this code to onCreate()

    Closeable sss = new Socket();     if (!(sss instanceof Closeable)) {         throw new RuntimeException("Something unexpected happened");     } 

The imports are:

import java.io.Closeable; import java.net.Socket; 

The code compiles, but I am getting the exception:

E/AndroidRuntime( 8293): java.lang.RuntimeException: Unable to start activity...: java.lang.RuntimeException: Something unexpected happened ... E/AndroidRuntime( 8293): Caused by: java.lang.RuntimeException: Something unexpected happened ... 

In a different context, the glitch causes a java.lang.ArrayStoreException (namely, java.lang.ArrayStoreException: java.net.Socket cannot be stored in an array of type java.io.Closeable[]).

Am I missing something? Any idea what to do?

EDIT Similarly, when DatagramSocket is used as MyClass for MyClass, it causes java.lang.IncompatibleClassChangeError: interface not implemented.

回答1:

This issue occurs on Android API levels prior to 19. On affected versions, Socket does not implement Closeable.

Sources:



回答2:

Socket is not itself closeable, but both of its streams are. And closing either stream will close the Socket



回答3:

For future readers, I want to clarify something that was assumed to be evident by everyone in this discussion:

How could I assign Closeable sss = new Socket(); if Socket is not Closeable?

The API requirements specified in AndroidManifest.xml are:

and the device reports

android.os.Build.VERSION.SDK_INT=16 

The code was compiled for API level 19, this is why it was successfully compiled. But it was run on API level 16, and this is why it failed.

In other words, the compile-time check was performed for API19 on one computer (the desktop PC) while the run-time check was performed for API16 on another computer (the handheld device).



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!