1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.callbackparams.annotation.util;
18
19 import java.lang.annotation.Annotation;
20 import java.lang.reflect.Field;
21
22
23
24
25
26
27
28
29 public class EnumConstantDescriptor {
30
31 private final Field coreEnumField;
32
33 public EnumConstantDescriptor(final Enum<?> enumConstant) {
34 for (Field f : enumConstant.getDeclaringClass().getFields()) {
35 if (f.isEnumConstant()) {
36 if (false == f.isAccessible()) {
37 try {
38 f.setAccessible(true);
39 } catch (final SecurityException x) {
40
41 }
42 }
43 try {
44 if (enumConstant == f.get(null)) {
45 this.coreEnumField = f;
46 return;
47 }
48 } catch (Exception x) {
49 throw new Error(x);
50 }
51 }
52 }
53
54 throw new AssertionError("Unable to determine field for enum-constant "
55 + enumConstant);
56 }
57
58
59
60
61
62
63 public <A extends Annotation> A getAnnotation(Class<A> a) {
64 return getAnnotation(a, false);
65 }
66
67
68
69
70
71
72
73
74
75
76
77
78 public <A extends Annotation> A getAnnotation(
79 final Class<A> a, final boolean force) {
80 A annotation = coreEnumField.getAnnotation(a);
81 if (null != annotation) {
82 return annotation;
83 }
84 annotation = coreEnumField.getDeclaringClass().getAnnotation(a);
85 if (null != annotation) {
86 return annotation;
87 } else if (false == force) {
88 return null;
89 } else {
90 throw new AssertionError("Neither the enum-constant "
91 + coreEnumField.getName() + " nor its class "
92 + coreEnumField.getDeclaringClass() + " is annotated with "
93 + a);
94 }
95 }
96 }