Android Open Source - reflect-app Reflective Type Adapter Factory






From Project

Back to project page reflect-app.

License

The source code is released under:

Apache License

If you think the Android project reflect-app listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

/*
 * Copyright (C) 2011 Google Inc./*  w w w. j  a  v  a 2 s  .  c  o  m*/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.gson.internal.bind;

import com.google.gson.FieldNamingStrategy;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.annotations.SerializedName;
import com.google.gson.internal.$Gson$Types;
import com.google.gson.internal.ConstructorConstructor;
import com.google.gson.internal.Excluder;
import com.google.gson.internal.ObjectConstructor;
import com.google.gson.internal.Primitives;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Type adapter that reflects over the fields and methods of a class.
 */
public final class ReflectiveTypeAdapterFactory implements TypeAdapterFactory {
  private final ConstructorConstructor constructorConstructor;
  private final FieldNamingStrategy fieldNamingPolicy;
  private final Excluder excluder;

  public ReflectiveTypeAdapterFactory(ConstructorConstructor constructorConstructor,
      FieldNamingStrategy fieldNamingPolicy, Excluder excluder) {
    this.constructorConstructor = constructorConstructor;
    this.fieldNamingPolicy = fieldNamingPolicy;
    this.excluder = excluder;
  }

  public boolean excludeField(Field f, boolean serialize) {
    return !excluder.excludeClass(f.getType(), serialize) && !excluder.excludeField(f, serialize);
  }

  private String getFieldName(Field f) {
    SerializedName serializedName = f.getAnnotation(SerializedName.class);
    return serializedName == null ? fieldNamingPolicy.translateName(f) : serializedName.value();
  }

  public <T> TypeAdapter<T> create(Gson gson, final TypeToken<T> type) {
    Class<? super T> raw = type.getRawType();

    if (!Object.class.isAssignableFrom(raw)) {
      return null; // it's a primitive!
    }

    ObjectConstructor<T> constructor = constructorConstructor.get(type);
    return new Adapter<T>(constructor, getBoundFields(gson, type, raw));
  }

  private ReflectiveTypeAdapterFactory.BoundField createBoundField(
      final Gson context, final Field field, final String name,
      final TypeToken<?> fieldType, boolean serialize, boolean deserialize) {
    final boolean isPrimitive = Primitives.isPrimitive(fieldType.getRawType());

    // special casing primitives here saves ~5% on Android...
    return new ReflectiveTypeAdapterFactory.BoundField(name, serialize, deserialize) {
      final TypeAdapter<?> typeAdapter = context.getAdapter(fieldType);
      @SuppressWarnings({"unchecked", "rawtypes"}) // the type adapter and field type always agree
      @Override void write(JsonWriter writer, Object value)
          throws IOException, IllegalAccessException {
        Object fieldValue = field.get(value);
        TypeAdapter t =
          new TypeAdapterRuntimeTypeWrapper(context, this.typeAdapter, fieldType.getType());
        t.write(writer, fieldValue);
      }
      @Override void read(JsonReader reader, Object value)
          throws IOException, IllegalAccessException {
        Object fieldValue = typeAdapter.read(reader);
        if (fieldValue != null || !isPrimitive) {
          field.set(value, fieldValue);
        }
      }
    };
  }

  private Map<String, BoundField> getBoundFields(Gson context, TypeToken<?> type, Class<?> raw) {
    Map<String, BoundField> result = new LinkedHashMap<String, BoundField>();
    if (raw.isInterface()) {
      return result;
    }

    Type declaredType = type.getType();
    while (raw != Object.class) {
      Field[] fields = raw.getDeclaredFields();
      for (Field field : fields) {
        boolean serialize = excludeField(field, true);
        boolean deserialize = excludeField(field, false);
        if (!serialize && !deserialize) {
          continue;
        }
        field.setAccessible(true);
        Type fieldType = $Gson$Types.resolve(type.getType(), raw, field.getGenericType());
        BoundField boundField = createBoundField(context, field, getFieldName(field),
            TypeToken.get(fieldType), serialize, deserialize);
        BoundField previous = result.put(boundField.name, boundField);
        if (previous != null) {
          throw new IllegalArgumentException(declaredType
              + " declares multiple JSON fields named " + previous.name);
        }
      }
      type = TypeToken.get($Gson$Types.resolve(type.getType(), raw, raw.getGenericSuperclass()));
      raw = type.getRawType();
    }
    return result;
  }

  static abstract class BoundField {
    final String name;
    final boolean serialized;
    final boolean deserialized;

    protected BoundField(String name, boolean serialized, boolean deserialized) {
      this.name = name;
      this.serialized = serialized;
      this.deserialized = deserialized;
    }

    abstract void write(JsonWriter writer, Object value) throws IOException, IllegalAccessException;
    abstract void read(JsonReader reader, Object value) throws IOException, IllegalAccessException;
  }

  public static final class Adapter<T> extends TypeAdapter<T> {
    private final ObjectConstructor<T> constructor;
    private final Map<String, BoundField> boundFields;

    private Adapter(ObjectConstructor<T> constructor, Map<String, BoundField> boundFields) {
      this.constructor = constructor;
      this.boundFields = boundFields;
    }

    @Override public T read(JsonReader in) throws IOException {
      if (in.peek() == JsonToken.NULL) {
        in.nextNull();
        return null;
      }

      T instance = constructor.construct();

      try {
        in.beginObject();
        while (in.hasNext()) {
          String name = in.nextName();
          BoundField field = boundFields.get(name);
          if (field == null || !field.deserialized) {
            in.skipValue();
          } else {
            field.read(in, instance);
          }
        }
      } catch (IllegalStateException e) {
        throw new JsonSyntaxException(e);
      } catch (IllegalAccessException e) {
        throw new AssertionError(e);
      }
      in.endObject();
      return instance;
    }

    @Override public void write(JsonWriter out, T value) throws IOException {
      if (value == null) {
        out.nullValue();
        return;
      }

      out.beginObject();
      try {
        for (BoundField boundField : boundFields.values()) {
          if (boundField.serialized) {
            out.name(boundField.name);
            boundField.write(out, value);
          }
        }
      } catch (IllegalAccessException e) {
        throw new AssertionError();
      }
      out.endObject();
    }
  }
}




Java Source Code List

com.google.gson.DefaultDateTypeAdapter.java
com.google.gson.ExclusionStrategy.java
com.google.gson.FieldAttributes.java
com.google.gson.FieldNamingPolicy.java
com.google.gson.FieldNamingStrategy.java
com.google.gson.GsonBuilder.java
com.google.gson.Gson.java
com.google.gson.InstanceCreator.java
com.google.gson.JsonArray.java
com.google.gson.JsonDeserializationContext.java
com.google.gson.JsonDeserializer.java
com.google.gson.JsonElement.java
com.google.gson.JsonIOException.java
com.google.gson.JsonNull.java
com.google.gson.JsonObject.java
com.google.gson.JsonParseException.java
com.google.gson.JsonParser.java
com.google.gson.JsonPrimitive.java
com.google.gson.JsonSerializationContext.java
com.google.gson.JsonSerializer.java
com.google.gson.JsonStreamParser.java
com.google.gson.JsonSyntaxException.java
com.google.gson.LongSerializationPolicy.java
com.google.gson.TreeTypeAdapter.java
com.google.gson.TypeAdapterFactory.java
com.google.gson.TypeAdapter.java
com.google.gson.annotations.Expose.java
com.google.gson.annotations.SerializedName.java
com.google.gson.annotations.Since.java
com.google.gson.annotations.Until.java
com.google.gson.annotations.package-info.java
com.google.gson.internal.ConstructorConstructor.java
com.google.gson.internal.Excluder.java
com.google.gson.internal.JsonReaderInternalAccess.java
com.google.gson.internal.LazilyParsedNumber.java
com.google.gson.internal.LinkedHashTreeMap.java
com.google.gson.internal.ObjectConstructor.java
com.google.gson.internal.Primitives.java
com.google.gson.internal.Streams.java
com.google.gson.internal.UnsafeAllocator.java
com.google.gson.internal.$Gson$Preconditions.java
com.google.gson.internal.$Gson$Types.java
com.google.gson.internal.bind.ArrayTypeAdapter.java
com.google.gson.internal.bind.CollectionTypeAdapterFactory.java
com.google.gson.internal.bind.DateTypeAdapter.java
com.google.gson.internal.bind.JsonTreeReader.java
com.google.gson.internal.bind.JsonTreeWriter.java
com.google.gson.internal.bind.MapTypeAdapterFactory.java
com.google.gson.internal.bind.ObjectTypeAdapter.java
com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.java
com.google.gson.internal.bind.SqlDateTypeAdapter.java
com.google.gson.internal.bind.TimeTypeAdapter.java
com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.java
com.google.gson.internal.bind.TypeAdapters.java
com.google.gson.internal.package-info.java
com.google.gson.reflect.TypeToken.java
com.google.gson.reflect.package-info.java
com.google.gson.stream.JsonReader.java
com.google.gson.stream.JsonScope.java
com.google.gson.stream.JsonToken.java
com.google.gson.stream.JsonWriter.java
com.google.gson.stream.MalformedJsonException.java
com.google.gson.package-info.java
com.pontydysgu.data.Answer.java
com.pontydysgu.data.LoginData.java
com.pontydysgu.data.QuestionStack.java
com.pontydysgu.data.Question.java
com.pontydysgu.data.StackArray.java
com.pontydysgu.gui.StackArrayAdapter.java
com.pontydysgu.pontylearningapp.DataService.java
com.pontydysgu.pontylearningapp.Login.java
com.pontydysgu.pontylearningapp.QuestionCycle.java
com.pontydysgu.pontylearningapp.Stackoverview.java
com.pontydysgu.webio.GetWebRequest.java
com.pontydysgu.webio.LoginService.java
com.pontydysgu.webio.PontyService.java
com.pontydysgu.webio.RetrieveStacksCallback.java
com.pontydysgu.webio.RetrieveStacksTask.java
com.pontydysgu.webio.SubmitAnswerCallback.java
com.pontydysgu.webio.SubmitAnswerTask.java