TwrForVariable1.java revision 2726:f62d01419621
1/* @test /nodynamiccopyright/
2 * @bug 7196163
3 * @summary Verify that variables can be used as operands to try-with-resources
4 * @compile/fail/ref=TwrForVariable1.out -source 8 -XDrawDiagnostics -Xlint:-options TwrForVariable1.java
5 * @compile TwrForVariable1.java
6 * @run main TwrForVariable1
7 */
8public class TwrForVariable1 implements AutoCloseable {
9    private static int closeCount = 0;
10    public static void main(String... args) {
11        TwrForVariable1 v = new TwrForVariable1();
12
13        try (v) {
14            assertCloseCount(0);
15        }
16        try (/**@deprecated*/v) {
17            assertCloseCount(1);
18        }
19        try (v.finalWrapper.finalField) {
20            assertCloseCount(2);
21        } catch (Exception ex) {
22        }
23        try (new TwrForVariable1() { }.finalWrapper.finalField) {
24            assertCloseCount(3);
25        } catch (Exception ex) {
26        }
27        try ((args.length > 0 ? v : new TwrForVariable1()).finalWrapper.finalField) {
28            assertCloseCount(4);
29        } catch (Exception ex) {
30        }
31        try {
32            throw new CloseableException();
33        } catch (CloseableException ex) {
34            try (ex) {
35                assertCloseCount(5);
36            }
37        }
38
39        assertCloseCount(6);
40    }
41
42    static void assertCloseCount(int expectedCloseCount) {
43        if (closeCount != expectedCloseCount)
44            throw new RuntimeException("bad closeCount: " + closeCount +
45                                       "; expected: " + expectedCloseCount);
46    }
47
48    public void close() {
49        closeCount++;
50    }
51
52    final FinalWrapper finalWrapper = new FinalWrapper();
53
54    static class FinalWrapper {
55        public final AutoCloseable finalField = new AutoCloseable() {
56            @Override
57            public void close() throws Exception {
58                closeCount++;
59            }
60        };
61    }
62
63    static class CloseableException extends Exception implements AutoCloseable {
64        @Override
65        public void close() {
66            closeCount++;
67        }
68    }
69}
70