由于使用到ElasticSearch,很多jar包都是大佬封装好给我们直接使用的,所以不得不开始探寻jar的源码,
从中也学会了一些骚操作。
这是我公司封装的一个连接操作ElasticSearch的client类,可以看到其接口继承了一个Closeable接口。
public interface EsClient extends Closeable
package java.io;
import java.io.IOException;
/**
* A {@code Closeable} is a source or destination of data that can be closed.
* The close method is invoked to release resources that the object is
* holding (such as open files).
*
* @since 1.5
*/
public interface Closeable extends AutoCloseable {
/**
* Closes this stream and releases any system resources associated
* with it. If the stream is already closed then invoking this
* method has no effect.
*
* <p> As noted in {@link AutoCloseable#close()}, cases where the
* close may fail require careful attention. It is strongly advised
* to relinquish the underlying resources and to internally
* <em>mark</em> the {@code Closeable} as closed, prior to throwing
* the {@code IOException}.
*
* @throws IOException if an I/O error occurs
*/
public void close() throws IOException;
}
其意思很明确,就是关闭stream和资源的一个方法。我们打开InputStream也可以看到其继承了这个接口。我们平常使用完流以后都会close,关闭资源占用。
在java1.7以后其实try-catch有了一个骚操作,我们可以将需要关闭的流资源等,放在try(括号里边)。
例:
import java.io.IOException;
import java.io.InputStream;
public class TestTry {
public static void main(String[] args) {
try(
InputStream inputStream = new MyInputStream();
) {
System.out.println("执行体");
}catch (Exception e){
e.printStackTrace();
}
}
public static class MyInputStream extends InputStream{
@Override
public int read() throws IOException {
return 0;
}
@Override
public void close() throws IOException {
System.out.println("执行了关闭");
super.close();
}
}
}
执行结果:
执行体
执行了关闭
Process finished with exit code 0