简体   繁体   English

为什么Socket在运行时不是可闭合的实例?

[英]why a Socket is not instanceof Closeable at runtime?

In an Android app, I added this code to onCreate() 在Android应用中,我将此代码添加到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[] ). 在不同的上下文中,毛刺导致java.lang.ArrayStoreException (即, java.lang.ArrayStoreException:java.net.Socket不能存储在java.io.Closeable []类型的数组中 )。

Am I missing something? 我错过了什么吗? Any idea what to do? 知道该怎么办?

EDIT Similarly, when DatagramSocket is used as MyClass<DatagramSocket> for MyClass<T extends Closeable> , it causes java.lang.IncompatibleClassChangeError: interface not implemented . 编辑类似地,当DatagramSocket用作MyClass<DatagramSocket> for MyClass<T extends Closeable> ,它会导致java.lang.IncompatibleClassChangeError:接口未实现

This issue occurs on Android API levels prior to 19. On affected versions, Socket does not implement Closeable. 此问题发生在19之前的Android API级别上。在受影响的版本上,Socket未实现Closeable。

Sources: 资料来源:

Socket is not itself closeable, but both of its streams are. 套接字本身不可关闭,但它的两个流都是。 And closing either stream will close the Socket 关闭任一流将关闭Socket

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(); 我怎么能指定Closeable sss = new Socket(); if Socket is not Closeable ? 如果Socket不可Closeable

The API requirements specified in AndroidManifest.xml are: AndroidManifest.xml中指定的API要求是:

<uses-sdk
    android:minSdkVersion="14"
    android:targetSdkVersion="19" />

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. 代码是针对API级别19编译的,这就是它成功编译的原因。 But it was run on API level 16, and this is why it failed. 但是它在API级别16上运行,这就是它失败的原因。

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). 换句话说,在一台计算机(台式PC)上对API19执行编译时检查,同时在另一台计算机(手持设备)上对API16执行运行时检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM