Skip to content

Commit

Permalink
SerializedName annotation workaround for obfuscated enums by ProGuard
Browse files Browse the repository at this point in the history
SerializedName annotation cannot be applied on enums when obfuscated by
proguard.
Because EnumTypeAdapter cannot find obfuscated enum constant field
with its name.
So, EnumTypeAdapter should load annotation from DeclaredFields, not EnumConstants
  • Loading branch information
ganadist committed Mar 22, 2019
1 parent 8bf2949 commit e9093a0
Showing 1 changed file with 13 additions and 3 deletions.
16 changes: 13 additions & 3 deletions gson/src/main/java/com/google/gson/internal/bind/TypeAdapters.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -776,9 +777,14 @@ private static final class EnumTypeAdapter<T extends Enum<T>> extends TypeAdapte

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()) {
Expand All @@ -788,7 +794,11 @@ public EnumTypeAdapter(Class<T> classOfT) {
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);
}
}
Expand Down

0 comments on commit e9093a0

Please sign in to comment.