KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > springframework > core > enums > StaticLabeledEnumResolver


1 /*
2  * Copyright 2002-2005 the original author or authors.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16
17 package org.springframework.core.enums;
18
19 import java.lang.reflect.Field JavaDoc;
20 import java.lang.reflect.Modifier JavaDoc;
21 import java.util.Set JavaDoc;
22 import java.util.TreeSet JavaDoc;
23
24 import org.springframework.util.Assert;
25
26 /**
27  * LabeledEnumResolver that resolves statically defined enumerations.
28  * Static implies all enum instances were defined within Java code,
29  * implementing the type-safe enum pattern.
30  *
31  * @author Keith Donald
32  * @author Juergen Hoeller
33  * @since 1.2.2
34  */

35 public class StaticLabeledEnumResolver extends AbstractCachingLabeledEnumResolver {
36
37     /**
38      * Shared <code>StaticLabeledEnumResolver</code> singleton instance.
39      */

40     private static final StaticLabeledEnumResolver INSTANCE = new StaticLabeledEnumResolver();
41
42
43     /**
44      * Return the shared <code>StaticLabeledEnumResolver</code> singleton instance.
45      * Mainly for resolving unique StaticLabeledEnum references on deserialization.
46      * @see StaticLabeledEnum
47      */

48     public static StaticLabeledEnumResolver instance() {
49         return INSTANCE;
50     }
51
52
53     protected Set JavaDoc findLabeledEnums(Class JavaDoc type) {
54         Set JavaDoc typeEnums = new TreeSet JavaDoc();
55         Field JavaDoc[] fields = type.getFields();
56         for (int i = 0; i < fields.length; i++) {
57             Field JavaDoc field = fields[i];
58             if (Modifier.isStatic(field.getModifiers()) && Modifier.isPublic(field.getModifiers())) {
59                 if (type.isAssignableFrom(field.getType())) {
60                     try {
61                         Object JavaDoc value = field.get(null);
62                         Assert.isTrue(value instanceof LabeledEnum, "Field value must be a LabeledEnum instance");
63                         typeEnums.add(value);
64                     }
65                     catch (IllegalAccessException JavaDoc e) {
66                         logger.warn("Unable to access field value " + field, e);
67                     }
68                 }
69             }
70         }
71         return typeEnums;
72     }
73
74 }
75
Popular Tags