jdk中的AutoCloseable使用

jdk中的AutoCloseable接口使用

举个例子:

public class AutoClient implements AutoCloseable{
	@Override
	public void close() throws Exception {
		System.out.println("I'm closed.");
	}
}

测试:

public class AutoClientTest {

	public static void main(String[] args) {
		try (AutoClient client = new AutoClient()){

			System.out.println("I'm doing something.");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

结果:

I'm doing something.
I'm closed.

AutoCloseable的close方法需要和try(){}一起使用

发布了76 篇原创文章 · 获赞 66 · 访问量 51万+

猜你喜欢

转载自blog.csdn.net/u013887008/article/details/103357579
今日推荐