EnumImplicitPrivateConstructor.java revision 0:9a66ca7c79fa
1/*
2 * Copyright 2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
20 * CA 95054 USA or visit www.sun.com if you need additional information or
21 * have any questions.
22 */
23
24/*
25 * @test
26 * @bug 5009601 5010455 5005748
27 * @summary enum constructors can be declared private
28 * @author Joseph D. Darcy
29 *
30 * @compile -source 1.5 EnumImplicitPrivateConstructor.java
31 * @run main EnumImplicitPrivateConstructor
32 */
33
34import java.util.*;
35import java.lang.reflect.*;
36import java.lang.annotation.*;
37
38/*
39 * Arguably, only the final and abstract should be held in
40 * ExpectedModifiers; whether or not an enum should be static could be
41 * inferred from getDeclaringClass and working versions of
42 * getEnclosingMethod and getEnclosingConstructor.  I.e. if
43 * getDeclaringClass, getEnclosingMethod, and getEnclosingConstructor
44 * were all null, the enum is a top-level class and should not be
45 * static; otherwise, it should be static.
46 */
47
48@ExpectedModifiers(Modifier.FINAL)
49public enum EnumImplicitPrivateConstructor {
50    RED(255, 0, 0),
51    GREEN(0, 255, 0),
52    BLUE(0, 0, 255);
53
54    private int r, g, b;
55    EnumImplicitPrivateConstructor(int r, int g, int b) {
56        this.r = r;
57        this.g = g;
58        this.b = b;
59    }
60
61    /*
62     * Using reflection, Verify that
63     * 1. all non-synthetic constructors of enum classes are marked as private.
64     * 2. top-level enum classes are marked as static
65     * 3. enum's are marked final and abstract as appropriate
66     * 4. enum constructors *cannot* be invoked reflectively
67     */
68    public static void main(String argv[]) throws Exception {
69        boolean passed = true;
70
71        Collection<Class> classes = new LinkedHashSet<Class>();
72
73        classes.add(Class.forName("EnumImplicitPrivateConstructor"));
74        classes.add(Class.forName("EnumImplicitPrivateConstructor$AnotherEnum"));
75        classes.add(Class.forName("EnumImplicitPrivateConstructor$YetAnotherEnum"));
76        classes.add(Class.forName("EnumImplicitPrivateConstructor$OneMoreEnum"));
77
78        // Add classes of specialized enum constants
79        for(Enum e: YetAnotherEnum.values())
80            classes.add(e.getClass());
81
82        for(Class clazz: classes) {
83            System.out.println("Testing class " + clazz);
84
85            int classModifiers = clazz.getModifiers();
86
87            // Why is this cast needed?
88            ExpectedModifiers em = (ExpectedModifiers)clazz.getAnnotation(ExpectedModifiers.class);
89            if (em != null) {
90                System.out.println("\tTesting expected modifiers");
91                int expected = em.value();
92
93                if (expected != (classModifiers & (Modifier.ABSTRACT|Modifier.FINAL|Modifier.STATIC))) {
94                    passed = false;
95                    System.out.println("\tFAILED: Expected 0x" + Integer.toHexString(expected) +
96                                       " got 0x" +Integer.toHexString(classModifiers));
97                }
98            }
99
100            for(Constructor ctor: clazz.getDeclaredConstructors() ) {
101                System.out.println("\tTesting constructor " + ctor);
102
103                // We don't need no stinkin' access rules
104                try {
105                    ctor.setAccessible(true);
106                } catch (java.security.AccessControlException ex) {
107                }
108
109                int modifiers = ctor.getModifiers();
110
111                /*
112                 * If clazz is for a specialized enum constant, the
113                 * class will have the ENUM bit set but clazz.isEnum()
114                 * will be false.  A constructor in such a class must
115                 * be non-private to allow the parent class to call
116                 * the constructor.  Therefore, only impose the
117                 * private constructor check for genuine isEnum
118                 * classes.
119                 */
120                if (clazz.isEnum()) {
121                    if ((modifiers & Modifier.PRIVATE) == 0 &&
122                        ! ctor.isSynthetic() ) {
123                        passed = false;
124                        System.out.println("\tFAILED: Constructor not marked private: modifiers 0x" +
125                                           Integer.toHexString(modifiers));
126                    }
127                }
128
129                try {
130                    // Should get exception trying to invoke
131                    Object o = null;
132                    try {
133                        o = ctor.newInstance("abc", 123);
134                    } catch (IllegalAccessException ex) {
135                    }
136
137                    /*
138                     * A better test would query the number (and type)
139                     * of parameters and create an appropriate
140                     * argument list since IllegalArgumentException can be
141                     * thrown for just using the wrong number of arguments.
142                     */
143
144                    if (o != null) {
145                        passed = false;
146                        System.err.println("Error: Created new enum object!");
147                        System.err.println(o.getClass());
148                        System.err.println(o.toString());
149                    }
150                } catch (IllegalArgumentException iae) {}
151
152            }
153        }
154
155        if (!passed)
156            throw new RuntimeException("Error during testing.");
157    }
158
159
160    /*
161     * Should be final and not abstract.
162     */
163    @ExpectedModifiers(Modifier.FINAL|Modifier.STATIC)
164    enum AnotherEnum {
165        YELLOW,
166        CYAN,
167        MAGENTA;
168    }
169
170    /*
171     * Should be neither final nor abstract.
172     */
173    @ExpectedModifiers(Modifier.STATIC)
174    enum YetAnotherEnum {
175        GREEN {
176            int value(){ return 1;}
177        },
178
179        ORANGE {
180            int value(){ return 2;}
181        },
182
183        VIOLET {
184            int value(){ return 3;}
185        };
186
187        int value(){ return 0;}
188    }
189
190    /*
191     * Should be abstract and not final.
192     */
193    @ExpectedModifiers(Modifier.ABSTRACT|Modifier.STATIC)
194    enum OneMoreEnum {
195        SANGUINE {
196            int value(){ return 1;}
197        },
198
199        VERDANT {
200            int value(){ return 2;}
201        },
202
203        CERULEAN {
204            int value(){ return 3;}
205        };
206
207        abstract int value();
208    }
209}
210
211@Retention(RetentionPolicy.RUNTIME)
212@interface ExpectedModifiers {
213    int value();
214}
215