Java 在Line接口中,我必须为所有实例调用close(),还是只有在Line打开时才调用?

Java 在Line接口中,我必须为所有实例调用close(),还是只有在Line打开时才调用?,java,javasound,try-with-resources,autocloseable,Java,Javasound,Try With Resources,Autocloseable,根据自动关闭接口的定义, 我必须为所有实例调用close()。 i、 我必须这样写 try(A a = new A()){ //do something } 在java.sound.sampled.SourceDataLine接口中, 或者更常见的是,在java.sound.sampled.Line接口中, 是否需要为所有实例调用close(), 或者只有在调用了open()之后,我才能调用close() 如果官方文件明确规定我必须在打开时关闭, 我想这样写。 但我找不到提及的地方 /

根据
自动关闭接口的定义,
我必须为所有实例调用
close()

i、 我必须这样写

try(A a = new A()){
    //do something
}
java.sound.sampled.SourceDataLine
接口中,
或者更常见的是,在
java.sound.sampled.Line
接口中,
是否需要为所有实例调用
close()

或者只有在调用了
open()
之后,我才能调用
close()

如果官方文件明确规定我必须在<代码>打开时关闭<代码>,
我想这样写。 但我找不到提及的地方

//can I write like this ?  

SourceDataLine sdl;
try{
    sdl = AudioSystem.getSourceDataLine(audioFormat);
    sdl.open(audioFormat,bufferSize);
}catch(LineUnavailableException ex){
    throw new RuntimeException(null,ex);
}
try(SourceDataLine sdlInTryWithResources = sdl){
    //do something
}  

看来你想得太多了

仅仅使用资源进行图像尝试是不存在的,并且写下您的代码,就像您在Java1.7之前所做的那样

可以肯定的是,你最终会得到这样的结果:

Whatever somethingThatNeedsClosing = null;
try {
  somethingThatNeedsClosing = ...
  somethingThatNeedsClosing.whatever();
} catch (NoIdeaException e) {
  error handling
} finally {
  if (somethingThatNeedsClosing != null) {
    somethingThatNeedsClosing.close()
  }
}
Try with resources只允许您相应地减少这个示例

换句话说:try with resources允许您定义一个(或多个)将在try块中使用的资源;这将最终结束。如:为try声明的每个和任何资源。。。将关闭


更具体地说:不要考虑资源的其他实例。把注意力集中在你目前正在处理的事情上。

你似乎想得太多了

仅仅使用资源进行图像尝试是不存在的,并且写下您的代码,就像您在Java1.7之前所做的那样

可以肯定的是,你最终会得到这样的结果:

Whatever somethingThatNeedsClosing = null;
try {
  somethingThatNeedsClosing = ...
  somethingThatNeedsClosing.whatever();
} catch (NoIdeaException e) {
  error handling
} finally {
  if (somethingThatNeedsClosing != null) {
    somethingThatNeedsClosing.close()
  }
}
Try with resources只允许您相应地减少这个示例

换句话说:try with resources允许您定义一个(或多个)将在try块中使用的资源;这将最终结束。如:为try声明的每个和任何资源。。。将关闭


更具体地说:不要考虑资源的其他实例。专注于您当前正在处理的问题。

您实际的问题应该是“当数据线尚未打开时调用
close()
是否有害?”答案是“否”,因此您可以简单地使用

try(SourceDataLine sdl = AudioSystem.getSourceDataLine(audioFormat)) {
    sdl.open(audioFormat, bufferSize);
    // work with sdl
}
catch(LineUnavailableException ex) {
    throw new RuntimeException(ex);
}

请注意,
javax.sound.sampled.Line
在Java 7中被故意更改为扩展
AutoCloseable
,其唯一目的是允许在try-with-resource语句中使用资源。

您实际的问题应该是“当数据行未打开时调用
close()
是否有害?”答案是“不”,所以你可以简单地使用

try(SourceDataLine sdl = AudioSystem.getSourceDataLine(audioFormat)) {
    sdl.open(audioFormat, bufferSize);
    // work with sdl
}
catch(LineUnavailableException ex) {
    throw new RuntimeException(ex);
}

请注意,
javax.sound.sampled.Line
在Java 7中被故意更改为扩展
AutoCloseable
,其唯一目的是允许在try-with-resource语句中使用资源。

try-with-resources是为了稍微清理代码而发明的,不是为了让它变得更复杂…尝试使用资源是为了清理代码而发明的,不是为了让它变得更复杂。。。