提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
AutoCloseable资源类
public class Main { public static void main(String[] args) { // Its close() method will be called automatically *//**from NowJava.com - 时代Java**/ try (MyResource mr = new MyResource(2, false)) { mr.use(); mr.use(); } try (MyResource mr = new MyResource(2, true)) { mr.use(); mr.use(); } } } class MyResource implements AutoCloseable { private int score; private boolean errorOut; /** 来 自 nowjava.com**/ public MyResource(int level, boolean exceptionOnClose) { this.score = level; this.errorOut = exceptionOnClose; System.out.println("Creating MyResource. Level = " + level); } public void use() { if (score <= 0) { throw new RuntimeException("Low in level."); } System.out.println("Using MyResource level " + this.score); score--; } @Override public