import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapterFactory; import com.google.gson.reflect.TypeToken; public final class AutoValueAdapterFactory implements TypeAdapterFactory { @SuppressWarnings("unchecked") @Override public TypeAdapter create(Gson gson, TypeToken type) { Class rawType = type.getRawType(); if (!rawType.isAnnotationPresent(AutoGson.class)) { return null; } String packageName = rawType.getPackage().getName(); String className = rawType.getName().substring(packageName.length() + 1).replace('$', '_'); String autoValueName = packageName + ".AutoValue_" + className; try { Class autoValueType = Class.forName(autoValueName); return (TypeAdapter) gson.getAdapter(autoValueType); } catch (ClassNotFoundException e) { throw new RuntimeException("Could not load AutoValue type " + autoValueName, e); } } }