Tue, 20 Dec 2016 15:24:55 -0800
Added tag jdk8u152-b00 for changeset 03e31cfcd499
1 /*
2 * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 */
24 /*
25 * @test
26 * @bug 8023945
27 * @summary javac wrongly allows a subclass of an anonymous class
28 * @library /tools/javac/lib
29 * @build ToolBox
30 * @run main AnonymousSubclassTest
31 */
33 import java.util.ArrayList;
34 import java.io.IOException;
36 public class AnonymousSubclassTest {
37 public static void main(String... args) throws Exception {
38 new AnonymousSubclassTest().run();
39 }
41 // To trigger the error we want, first we need to compile
42 // a class with an anonymous inner class: Foo$1.
43 final String foo =
44 "public class Foo {" +
45 " void m() { Foo f = new Foo() {}; }" +
46 "}";
48 // Then, we try to subclass the anonymous class
49 // Note: we must do this in two classes because a different
50 // error will be generated if we don't load Foo$1 through the
51 // class reader.
52 final String test1 =
53 "public class Test1 {" +
54 " void m() {"+
55 " Foo f1 = new Foo();"+
56 " Foo f2 = new Foo$1(f1) {};"+
57 " }" +
58 "}";
60 final String test2 =
61 "public class Test2 {" +
62 " class T extends Foo$1 {" +
63 " public T(Foo f) { super(f); }" +
64 " }"+
65 "}";
67 void compOk(String code) throws Exception {
68 ToolBox.javac(new ToolBox.JavaToolArgs().setSources(code));
69 }
71 void compFail(String code) throws Exception {
72 ArrayList<String> errors = new ArrayList<>();
73 ToolBox.JavaToolArgs args = new ToolBox.JavaToolArgs();
74 args.setSources(code)
75 .appendArgs("-cp", ".", "-XDrawDiagnostics")
76 .set(ToolBox.Expect.FAIL)
77 .setErrOutput(errors);
78 ToolBox.javac(args);
80 if (!errors.get(0).contains("cant.inherit.from.anon")) {
81 System.out.println(errors.get(0));
82 throw new Exception("test failed");
83 }
84 }
86 void run() throws Exception {
87 compOk(foo);
88 compFail(test1);
89 compFail(test2);
90 }
91 }