Make EnumTypeAdapter friendly with obfuscation

When enum value was obfuscated by proguard, EnumTypeAdapter raise NoSuchFieldException even if apply SerializedName annotation.
Because EnumTypeAdapter cannot find obfuscated enum constant field with its name.
This commit is contained in:
YOUNG CHA 2019-03-22 17:11:11 +09:00 committed by YOUNG HO CHA
parent 63e747f7f4
commit 68f99f2440

View File

@ -17,6 +17,7 @@
package com.google.gson.internal.bind;
import java.io.IOException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.InetAddress;
@ -776,9 +777,14 @@ public final class TypeAdapters {
public EnumTypeAdapter(Class<T> classOfT) {
try {
for (T constant : classOfT.getEnumConstants()) {
for (Field field : classOfT.getDeclaredFields()) {
if (!field.isEnumConstant()) {
continue;
}
field.setAccessible(true);
T constant = (T)(field.get(null));
String name = constant.name();
SerializedName annotation = classOfT.getField(name).getAnnotation(SerializedName.class);
SerializedName annotation = field.getAnnotation(SerializedName.class);
if (annotation != null) {
name = annotation.value();
for (String alternate : annotation.alternate()) {
@ -788,7 +794,11 @@ public final class TypeAdapters {
nameToConstant.put(name, constant);
constantToName.put(constant, name);
}
} catch (NoSuchFieldException e) {
} catch (IllegalAccessException e) {
throw new AssertionError(e);
} catch (NullPointerException e) {
throw new AssertionError(e);
} catch (ExceptionInInitializerError e) {
throw new AssertionError(e);
}
}