2
|
1 |
// Copyright (c) 2009 The Chromium Authors. All rights reserved.
|
|
2 |
// Use of this source code is governed by a BSD-style license that can be
|
|
3 |
// found in the LICENSE file.
|
|
4 |
|
|
5 |
package org.chromium.sdk.internal.protocolparser.dynamicimpl;
|
|
6 |
|
|
7 |
import java.lang.reflect.InvocationTargetException;
|
|
8 |
import java.lang.reflect.Method;
|
|
9 |
|
|
10 |
import org.chromium.sdk.internal.protocolparser.JsonProtocolModelParseException;
|
|
11 |
import org.chromium.sdk.internal.protocolparser.JsonProtocolParseException;
|
|
12 |
|
|
13 |
class EnumParser<T extends Enum<T>> extends QuickParser<T> {
|
|
14 |
public static <T extends Enum<T>> EnumParser<T> create(Class<T> enumTypeClass,
|
|
15 |
boolean isNullable) throws JsonProtocolModelParseException {
|
|
16 |
return new EnumParser<T>(enumTypeClass, isNullable);
|
|
17 |
}
|
|
18 |
|
|
19 |
private final Method methodValueOf;
|
|
20 |
private final boolean isNullable;
|
|
21 |
private final Class<T> enumClass;
|
|
22 |
|
|
23 |
private EnumParser(Class<T> enumClass, boolean isNullable)
|
|
24 |
throws JsonProtocolModelParseException {
|
|
25 |
this.enumClass = enumClass;
|
|
26 |
this.isNullable = isNullable;
|
|
27 |
try {
|
|
28 |
this.methodValueOf = enumClass.getMethod("valueOf", String.class);
|
|
29 |
} catch (NoSuchMethodException e) {
|
|
30 |
throw new JsonProtocolModelParseException(
|
|
31 |
"Failed to find valueOf method for parsing strings", e);
|
|
32 |
}
|
|
33 |
}
|
|
34 |
|
|
35 |
@Override
|
|
36 |
public T parseValueQuick(Object value) throws JsonProtocolParseException {
|
|
37 |
if (isNullable && value == null) {
|
|
38 |
return null;
|
|
39 |
}
|
|
40 |
if (value instanceof String == false) {
|
|
41 |
throw new JsonProtocolParseException("String value expected");
|
|
42 |
}
|
|
43 |
String stringValue = (String) value;
|
|
44 |
T result;
|
|
45 |
try {
|
|
46 |
result = enumClass.cast(methodValueOf.invoke(null, stringValue));
|
|
47 |
} catch (IllegalArgumentException e) {
|
|
48 |
throw new JsonProtocolParseException("Failed to parse enum constant " + stringValue, e);
|
|
49 |
} catch (IllegalAccessException e) {
|
|
50 |
throw new JsonProtocolParseException("Failed to call valueOf method", e);
|
|
51 |
} catch (InvocationTargetException e) {
|
|
52 |
throw new JsonProtocolParseException("Failed to call valueOf method", e);
|
|
53 |
}
|
|
54 |
if (result == null) {
|
|
55 |
throw new JsonProtocolParseException("Failed to parse value " + value + " as enum");
|
|
56 |
}
|
|
57 |
return result;
|
|
58 |
}
|
|
59 |
}
|