AnonymousSubclassTest.java revision 3294:9adfb22ff08f
1/* 2 * Copyright (c) 2014, 2015, 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 */ 23 24/* 25 * @test 26 * @bug 8023945 27 * @summary javac wrongly allows a subclass of an anonymous class 28 * @library /tools/lib 29 * @modules jdk.compiler/com.sun.tools.javac.api 30 * jdk.compiler/com.sun.tools.javac.file 31 * jdk.compiler/com.sun.tools.javac.main 32 * jdk.jdeps/com.sun.tools.javap 33 * @build ToolBox 34 * @run main AnonymousSubclassTest 35 */ 36 37public class AnonymousSubclassTest { 38 public static void main(String... args) throws Exception { 39 new AnonymousSubclassTest().run(); 40 } 41 42 ToolBox tb = new ToolBox(); 43 44 // To trigger the error we want, first we need to compile 45 // a class with an anonymous inner class: Foo$1. 46 final String foo = 47 "public class Foo {" + 48 " void m() { Foo f = new Foo() {}; }" + 49 "}"; 50 51 // Then, we try to subclass the anonymous class 52 // Note: we must do this in two classes because a different 53 // error will be generated if we don't load Foo$1 through the 54 // class reader. 55 final String test1 = 56 "public class Test1 {" + 57 " void m() {"+ 58 " Foo f1 = new Foo();"+ 59 " Foo f2 = new Foo$1(f1) {};"+ 60 " }" + 61 "}"; 62 63 final String test2 = 64 "public class Test2 {" + 65 " class T extends Foo$1 {" + 66 " public T(Foo f) { super(f); }" + 67 " }"+ 68 "}"; 69 70 void compOk(String code) throws Exception { 71 tb.new JavacTask() 72 .sources(code) 73 .run(); 74 } 75 76 void compFail(String code) throws Exception { 77 String errs = tb.new JavacTask() 78 .sources(code) 79 .classpath(".") 80 .options("-XDrawDiagnostics") 81 .run(ToolBox.Expect.FAIL) 82 .writeAll() 83 .getOutput(ToolBox.OutputKind.DIRECT); 84 85 if (!errs.contains("cant.inherit.from.anon")) { 86 throw new Exception("test failed"); 87 } 88 } 89 90 void run() throws Exception { 91 compOk(foo); 92 compFail(test1); 93 compFail(test2); 94 } 95} 96