19
19
20
20
import java .io .IOException ;
21
21
import java .lang .reflect .Type ;
22
- import java .util .HashMap ;
23
- import java .util .Map ;
24
22
25
23
import org .msgpack .MessageTypeException ;
26
24
import org .msgpack .annotation .MessagePackOrdinalEnum ;
31
29
import org .msgpack .template .TemplateRegistry ;
32
30
import org .msgpack .template .builder .TemplateBuildException ;
33
31
import org .msgpack .unpacker .Unpacker ;
32
+ import org .slf4j .Logger ;
33
+ import org .slf4j .LoggerFactory ;
34
34
35
35
36
36
public class ReflectionOrdinalEnumTemplateBuilder extends AbstractTemplateBuilder {
37
37
38
+ private static final Logger LOG = LoggerFactory .getLogger (ReflectionOrdinalEnumTemplateBuilder .class );
39
+
38
40
static class ReflectionOrdinalEnumTemplate <T > extends AbstractTemplate <T > {
39
41
private T [] entries ;
40
42
41
- private Map <T , Integer > reverse ;
42
-
43
43
ReflectionOrdinalEnumTemplate (Class <T > targetClass ) {
44
44
entries = targetClass .getEnumConstants ();
45
- reverse = new HashMap <T , Integer >();
46
- for (int i = 0 ; i < entries .length ; ++i ) {
47
- reverse .put (entries [i ], i );
48
- }
49
45
}
50
46
51
47
@ Override
52
48
public void write (Packer pk , T target , boolean required ) throws IOException {
53
- Integer ord = reverse .get (target );
54
- if (ord == null ) {
55
- throw new MessageTypeException ();
56
- }
57
- pk .writeInt ((int ) ord );
49
+ pk .writeInt (((Enum ) target ).ordinal ());
58
50
}
59
51
60
52
@ Override
61
53
public T read (Unpacker pac , T to , boolean required ) throws IOException , MessageTypeException {
62
- int ord = pac .readInt ();
63
- if (entries . length <= ord ) {
64
- throw new MessageTypeException ();
54
+ int ordinal = pac .readInt ();
55
+ if (ordinal < 0 || ordinal >= entries . length ) {
56
+ throw new MessageTypeException ("illegal ordinal" );
65
57
}
66
- return entries [ord ];
58
+ return entries [ordinal ];
67
59
}
68
60
}
69
61
@@ -73,8 +65,11 @@ public ReflectionOrdinalEnumTemplateBuilder(TemplateRegistry registry) {
73
65
74
66
@ Override
75
67
public boolean matchType (Type targetType ) {
76
- return AbstractTemplateBuilder .isAnnotated ((Class <?>) targetType , OrdinalEnum .class )
77
- || AbstractTemplateBuilder .isAnnotated ((Class <?>) targetType , MessagePackOrdinalEnum .class );
68
+ Class <?> targetClass = (Class <?>) targetType ;
69
+ boolean match = AbstractTemplateBuilder .isAnnotated (targetClass , OrdinalEnum .class )
70
+ || AbstractTemplateBuilder .isAnnotated (targetClass , MessagePackOrdinalEnum .class );
71
+ LOG .debug ("matched type: " + targetClass .getName ());
72
+ return match ;
78
73
}
79
74
80
75
@ Override
0 commit comments