Android Open Source - reflect-app Constructor Constructor






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.//from www  . j  a v a  2 s . c  om
 *
 * 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;

import com.google.gson.InstanceCreator;
import com.google.gson.JsonIOException;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.EnumSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;

/**
 * Returns a function that can construct an instance of a requested type.
 */
public final class ConstructorConstructor {
  private final Map<Type, InstanceCreator<?>> instanceCreators;

  public ConstructorConstructor(Map<Type, InstanceCreator<?>> instanceCreators) {
    this.instanceCreators = instanceCreators;
  }

  public <T> ObjectConstructor<T> get(TypeToken<T> typeToken) {
    final Type type = typeToken.getType();
    final Class<? super T> rawType = typeToken.getRawType();

    // first try an instance creator

    @SuppressWarnings("unchecked") // types must agree
    final InstanceCreator<T> typeCreator = (InstanceCreator<T>) instanceCreators.get(type);
    if (typeCreator != null) {
      return new ObjectConstructor<T>() {
        public T construct() {
          return typeCreator.createInstance(type);
        }
      };
    }

    // Next try raw type match for instance creators
    @SuppressWarnings("unchecked") // types must agree
    final InstanceCreator<T> rawTypeCreator =
        (InstanceCreator<T>) instanceCreators.get(rawType);
    if (rawTypeCreator != null) {
      return new ObjectConstructor<T>() {
        public T construct() {
          return rawTypeCreator.createInstance(type);
        }
      };
    }

    ObjectConstructor<T> defaultConstructor = newDefaultConstructor(rawType);
    if (defaultConstructor != null) {
      return defaultConstructor;
    }

    ObjectConstructor<T> defaultImplementation = newDefaultImplementationConstructor(type, rawType);
    if (defaultImplementation != null) {
      return defaultImplementation;
    }

    // finally try unsafe
    return newUnsafeAllocator(type, rawType);
  }

  private <T> ObjectConstructor<T> newDefaultConstructor(Class<? super T> rawType) {
    try {
      final Constructor<? super T> constructor = rawType.getDeclaredConstructor();
      if (!constructor.isAccessible()) {
        constructor.setAccessible(true);
      }
      return new ObjectConstructor<T>() {
        @SuppressWarnings("unchecked") // T is the same raw type as is requested
        public T construct() {
          try {
            Object[] args = null;
            return (T) constructor.newInstance(args);
          } catch (InstantiationException e) {
            // TODO: JsonParseException ?
            throw new RuntimeException("Failed to invoke " + constructor + " with no args", e);
          } catch (InvocationTargetException e) {
            // TODO: don't wrap if cause is unchecked!
            // TODO: JsonParseException ?
            throw new RuntimeException("Failed to invoke " + constructor + " with no args",
                e.getTargetException());
          } catch (IllegalAccessException e) {
            throw new AssertionError(e);
          }
        }
      };
    } catch (NoSuchMethodException e) {
      return null;
    }
  }

  /**
   * Constructors for common interface types like Map and List and their
   * subytpes.
   */
  @SuppressWarnings("unchecked") // use runtime checks to guarantee that 'T' is what it is
  private <T> ObjectConstructor<T> newDefaultImplementationConstructor(
      final Type type, Class<? super T> rawType) {
    if (Collection.class.isAssignableFrom(rawType)) {
      if (SortedSet.class.isAssignableFrom(rawType)) {
        return new ObjectConstructor<T>() {
          public T construct() {
            return (T) new TreeSet<Object>();
          }
        };
      } else if (EnumSet.class.isAssignableFrom(rawType)) {
        return new ObjectConstructor<T>() {
          @SuppressWarnings("rawtypes")
          public T construct() {
            if (type instanceof ParameterizedType) {
              Type elementType = ((ParameterizedType) type).getActualTypeArguments()[0];
              if (elementType instanceof Class) {
                return (T) EnumSet.noneOf((Class)elementType);
              } else {
                throw new JsonIOException("Invalid EnumSet type: " + type.toString());
              }
            } else {
              throw new JsonIOException("Invalid EnumSet type: " + type.toString());
            }
          }
        };
      } else if (Set.class.isAssignableFrom(rawType)) {
        return new ObjectConstructor<T>() {
          public T construct() {
            return (T) new LinkedHashSet<Object>();
          }
        };
      } else if (Queue.class.isAssignableFrom(rawType)) {
        return new ObjectConstructor<T>() {
          public T construct() {
            return (T) new LinkedList<Object>();
          }
        };
      } else {
        return new ObjectConstructor<T>() {
          public T construct() {
            return (T) new ArrayList<Object>();
          }
        };
      }
    }

    if (Map.class.isAssignableFrom(rawType)) {
      if (SortedMap.class.isAssignableFrom(rawType)) {
        return new ObjectConstructor<T>() {
          public T construct() {
            return (T) new TreeMap<Object, Object>();
          }
        };
      } else if (type instanceof ParameterizedType && !(String.class.isAssignableFrom(
          TypeToken.get(((ParameterizedType) type).getActualTypeArguments()[0]).getRawType()))) {
        return new ObjectConstructor<T>() {
          public T construct() {
            return (T) new LinkedHashMap<Object, Object>();
          }
        };
      } else {
        return new ObjectConstructor<T>() {
          public T construct() {
            return (T) new LinkedHashTreeMap<String, Object>();
          }
        };
      }
    }

    return null;
  }


  private <T> ObjectConstructor<T> newUnsafeAllocator(
      final Type type, final Class<? super T> rawType) {
    return new ObjectConstructor<T>() {
      private final UnsafeAllocator unsafeAllocator = UnsafeAllocator.create();
      @SuppressWarnings("unchecked")
      public T construct() {
        try {
          Object newInstance = unsafeAllocator.newInstance(rawType);
          return (T) newInstance;
        } catch (Exception e) {
          throw new RuntimeException(("Unable to invoke no-args constructor for " + type + ". "
              + "Register an InstanceCreator with Gson for this type may fix this problem."), e);
        }
      }
    };
  }

  @Override public String toString() {
    return instanceCreators.toString();
  }
}




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