Skip to content

Commit e8f0662

Browse files
author
Takanori Takase
committed
[MSGPACK-83] Gracefully handling new enum value with OrdinalEnum.
1 parent 383fe05 commit e8f0662

2 files changed

Lines changed: 33 additions & 5 deletions

File tree

src/main/java/org/msgpack/annotation/OrdinalEnum.java

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,24 @@
2222
import java.lang.annotation.RetentionPolicy;
2323
import java.lang.annotation.Target;
2424

25+
import org.msgpack.MessageTypeException;
26+
import org.msgpack.template.OrdinalEnumTemplate;
27+
2528
@Target(ElementType.TYPE)
2629
@Retention(RetentionPolicy.RUNTIME)
2730
public @interface OrdinalEnum {
31+
32+
/**
33+
* Specify whether the ordinal index lookup should be handled strictly or
34+
* not when mapping ordinal value to an enum value. By specifying true,
35+
* {@link MessageTypeException} will be thrown if the enum specified by the
36+
* ordinal value does not exist in this implementation. If false, then the
37+
* missing ordinal value treated as null, gracefully handling the lookup.
38+
* Default is true.
39+
*
40+
* @since 0.6.8
41+
* @see OrdinalEnumTemplate
42+
*/
43+
boolean strict() default true;
44+
2845
}

src/main/java/org/msgpack/template/OrdinalEnumTemplate.java

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,19 +21,23 @@
2121
import java.util.HashMap;
2222

2323
import org.msgpack.MessageTypeException;
24+
import org.msgpack.annotation.OrdinalEnum;
2425
import org.msgpack.packer.Packer;
2526
import org.msgpack.unpacker.Unpacker;
2627

2728
public class OrdinalEnumTemplate<T> extends AbstractTemplate<T> {
2829
protected T[] entries;
2930
protected HashMap<T, Integer> reverse;
31+
protected boolean strict;
3032

3133
public OrdinalEnumTemplate(Class<T> targetClass) {
3234
entries = targetClass.getEnumConstants();
3335
reverse = new HashMap<T, Integer>();
3436
for (int i = 0; i < entries.length; i++) {
3537
reverse.put(entries[i], i);
3638
}
39+
strict = !targetClass.isAnnotationPresent(OrdinalEnum.class)
40+
|| targetClass.getAnnotation(OrdinalEnum.class).strict();
3741
}
3842

3943
@Override
@@ -61,10 +65,17 @@ public T read(Unpacker pac, T to, boolean required) throws IOException,
6165
}
6266

6367
int ordinal = pac.readInt();
64-
if (entries.length <= ordinal) {
65-
throw new MessageTypeException(
66-
new IllegalArgumentException("ordinal: " + ordinal));
67-
}
68-
return entries[ordinal];
68+
69+
if (ordinal < entries.length) {
70+
return entries[ordinal];
71+
}
72+
73+
if (!strict) {
74+
return null;
75+
}
76+
77+
throw new MessageTypeException(new IllegalArgumentException("ordinal: "
78+
+ ordinal));
79+
6980
}
7081
}

0 commit comments

Comments
 (0)