TestAnonClassNames.java revision 2453:3dfd962149b2
1/*
2 * Copyright (c) 2010, 2013, 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 6449781 6930508
27 * @summary Test that reported names of anonymous classes are non-null.
28 * @author  Joseph D. Darcy
29 * @library /tools/javac/lib
30 * @build   JavacTestingAbstractProcessor TestAnonSourceNames
31 * @compile -processor TestAnonSourceNames TestAnonClassNames.java
32 * @run main TestAnonClassNames
33 */
34
35/*
36 * This test operates in phases to test retrieving the qualified name
37 * of anonymous classes from type elements modeling the anonymous
38 * class.  The type elements are generated using both source files and
39 * class files as the basis of constructing the elements.
40 *
41 * Source files will be tested by the @compile line which runs
42 * TestAnonSourceNames as an annotation processor over this file.
43 *
44 * Class files are tested by the @run command on this type.  This
45 * class gets the names of classes with different nesting kinds,
46 * including anonymous classes, and then invokes the compiler with an
47 * annotation processor having the class files names as inputs.  The
48 * compiler is invoked via the javax.tools mechanism.
49 */
50
51import java.lang.annotation.*;
52import javax.lang.model.element.*;
53import javax.annotation.processing.*;
54import javax.lang.model.SourceVersion;
55import javax.lang.model.element.*;
56import javax.lang.model.util.*;
57import javax.tools.*;
58import java.util.*;
59
60import static java.lang.annotation.RetentionPolicy.*;
61import static javax.lang.model.element.NestingKind.*;
62import static javax.lang.model.util.ElementFilter.*;
63import static javax.tools.Diagnostic.Kind.*;
64import static javax.tools.StandardLocation.*;
65
66@Nesting(TOP_LEVEL)
67public class TestAnonClassNames {
68    @Nesting(MEMBER)
69    static class MemberClass1{}
70
71    @Nesting(MEMBER)
72    class MemberClass2{}
73
74    @Nesting(MEMBER)
75    class Win$$AtVegas { } // Class with funny name.
76
77    public static void main(String... argv) {
78        @Nesting(LOCAL)
79        class LocalClass{};
80
81        Object o =  new @Nesting(ANONYMOUS) Object() { // An anonymous annotated class
82                public String toString() {
83                    return "I have no name!";
84                }
85            };
86
87        Class<?>[] classes = {
88            MemberClass1.class,
89            MemberClass2.class,
90            LocalClass.class,
91            Win$$AtVegas.class,
92            o.getClass(),
93            TestAnonClassNames.class,
94        };
95
96        List<String> names = new ArrayList<String>();
97        for(Class<?> clazz : classes) {
98            String name = clazz.getName();
99            Nesting annotation = clazz.getAnnotation(Nesting.class);
100            NestingKind expected = annotation == null ?
101                NestingKind.ANONYMOUS : annotation.value();
102            System.out.format("%s is %s%n", name, expected);
103            testClassName(name);
104            names.add(name);
105        }
106
107        // test all names together
108        testClassNames(names);
109
110        if (errors > 0)
111            throw new RuntimeException(errors + " errors occurred");
112    }
113
114    /**
115     * Perform annotation processing on the class file name and verify
116     * the existence of different flavors of class names when the
117     * input classes are modeled as elements.
118     */
119    static void testClassName(String className) {
120        testClassNames(Arrays.asList(className));
121    }
122
123    /**
124     * Perform annotation processing on a list of class file names and verify
125     * the existence of different flavors of class names when the
126     * input classes are modeled as elements.
127     */
128    static void testClassNames(List<String> classNames) {
129        System.out.println("test: " + classNames);
130
131        List<String> options = new ArrayList<String>();
132        options.add("-proc:only");
133        options.add("-classpath");
134        options.add(System.getProperty("test.classes"));
135
136        JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
137        JavaCompiler.CompilationTask compileTask =
138            javaCompiler.getTask(null, // Output
139                                 null, // File manager
140                                 null, // Diagnostics
141                                 options,
142                                 classNames,
143                                 null); // Sources
144        List<Processor> processors = new ArrayList<Processor>();
145        processors.add(new ClassNameProber());
146        compileTask.setProcessors(processors);
147        Boolean goodResult = compileTask.call();
148        if (!goodResult) {
149            error("Errors found during compile.");
150        }
151    }
152
153    static int errors = 0;
154
155    static void error(String msg) {
156        System.out.println("Error: " + msg);
157        errors++;
158    }
159}
160
161@Target({ElementType.TYPE, ElementType.TYPE_USE})
162@Retention(RUNTIME)
163@interface Nesting {
164    NestingKind value();
165}
166
167/**
168 * Probe at the various kinds of names of a type element.
169 */
170class ClassNameProber extends JavacTestingAbstractProcessor {
171    public ClassNameProber(){super();}
172
173    private boolean classesFound=false;
174
175    public boolean process(Set<? extends TypeElement> annotations,
176                           RoundEnvironment roundEnv) {
177        if (!roundEnv.processingOver()) {
178            for(TypeElement typeElt : typesIn(roundEnv.getRootElements())) {
179                classesFound = true;
180
181                // Verify different names are non-null; an NPE will
182                // result in failed compile status being reported.
183                NestingKind nestingKind = typeElt.getNestingKind();
184                System.out.printf("\tSimple name: ''%s''\tQualified Name: ''%s''\tKind ''%s''\tNesting ''%s''%n",
185                                  typeElt.getSimpleName().toString(),
186                                  typeElt.getQualifiedName().toString(),
187                                  typeElt.getKind().toString(),
188                                  nestingKind.toString());
189
190                Nesting annotation = typeElt.getAnnotation(Nesting.class);
191                NestingKind expected = annotation == null ?
192                    NestingKind.ANONYMOUS : annotation.value();
193
194                if (expected != nestingKind) {
195                    throw new RuntimeException("Mismatch of expected and reported nesting kind.");
196                }
197            }
198
199        }
200
201        if (!classesFound) {
202            throw new RuntimeException("Error: no classes processed.");
203        }
204        return true;
205    }
206}
207