Java 类java.lang.reflect.Type 实例源码

项目:bubichain-sdk-java    文件:TypeUtils.java   
private static boolean isAssignable(ParameterizedType lhsType, ParameterizedType rhsType){
    if (lhsType.equals(rhsType)) {
        return true;
    }

    Type[] lhsTypeArguments = lhsType.getActualTypeArguments();
    Type[] rhsTypeArguments = rhsType.getActualTypeArguments();

    if (lhsTypeArguments.length != rhsTypeArguments.length) {
        return false;
    }

    for (int size = lhsTypeArguments.length, i = 0; i < size; ++i) {
        Type lhsArg = lhsTypeArguments[i];
        Type rhsArg = rhsTypeArguments[i];

        if (!lhsArg.equals(rhsArg) &&
                !(lhsArg instanceof WildcardType && isAssignable((WildcardType) lhsArg, rhsArg))) {
            return false;
        }
    }

    return true;
}
项目:ditb    文件:ProtobufUtil.java   
/**
 * A utility used to get permissions for selected namespace.
 * <p>
 * It's also called by the shell, in case you want to find references.
 *
 * @param protocol the AccessControlService protocol proxy
 * @param namespace name of the namespace
 * @throws ServiceException
 */
public static List<UserPermission> getUserPermissions(RpcController controller,
    AccessControlService.BlockingInterface protocol,
    byte[] namespace) throws ServiceException {
  AccessControlProtos.GetUserPermissionsRequest.Builder builder =
    AccessControlProtos.GetUserPermissionsRequest.newBuilder();
  if (namespace != null) {
    builder.setNamespaceName(ByteStringer.wrap(namespace));
  }
  builder.setType(AccessControlProtos.Permission.Type.Namespace);
  AccessControlProtos.GetUserPermissionsRequest request = builder.build();
  AccessControlProtos.GetUserPermissionsResponse response =
    protocol.getUserPermissions(controller, request);
  List<UserPermission> perms = new ArrayList<UserPermission>(response.getUserPermissionCount());
  for (AccessControlProtos.UserPermission perm: response.getUserPermissionList()) {
    perms.add(ProtobufUtil.toUserPermission(perm));
  }
  return perms;
}
项目:Wechat-Group    文件:WxMpMaterialNewsBatchGetGsonAdapter.java   
@Override
public WxMpMaterialNewsBatchGetResult deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
  WxMpMaterialNewsBatchGetResult wxMpMaterialNewsBatchGetResult = new WxMpMaterialNewsBatchGetResult();
  JsonObject json = jsonElement.getAsJsonObject();
  if (json.get("total_count") != null && !json.get("total_count").isJsonNull()) {
    wxMpMaterialNewsBatchGetResult.setTotalCount(GsonHelper.getAsInteger(json.get("total_count")));
  }
  if (json.get("item_count") != null && !json.get("item_count").isJsonNull()) {
    wxMpMaterialNewsBatchGetResult.setItemCount(GsonHelper.getAsInteger(json.get("item_count")));
  }
  if (json.get("item") != null && !json.get("item").isJsonNull()) {
    JsonArray item = json.getAsJsonArray("item");
    List<WxMpMaterialNewsBatchGetResult.WxMaterialNewsBatchGetNewsItem> items = new ArrayList<>();
    for (JsonElement anItem : item) {
      JsonObject articleInfo = anItem.getAsJsonObject();
      items.add(WxMpGsonBuilder.create().fromJson(articleInfo, WxMpMaterialNewsBatchGetResult.WxMaterialNewsBatchGetNewsItem.class));
    }
    wxMpMaterialNewsBatchGetResult.setItems(items);
  }
  return wxMpMaterialNewsBatchGetResult;
}
项目:thrifty-retrofit-converter    文件:ThriftyConverterFactory.java   
@Override
@SuppressWarnings("unchecked")
public Converter<?, RequestBody> requestBodyConverter(Type type,
                                                      Annotation[] parameterAnnotations,
                                                      Annotation[] methodAnnotations,
                                                      Retrofit retrofit) {
    if (!(type instanceof Class<?>)) {
        return null;
    }
    Class<?> c = (Class<?>) type;
    if (!Struct.class.isAssignableFrom(c)) {
        return null;
    }
    Adapter adapter = getAdapter(c);
    return new ThriftyRequestBodyConverter<>(protocolType, adapter);
}
项目:spring-rest-commons-options    文件:DetailFieldCreatedStrategyFactory.java   
private static DetailFieldStrategy getGenericParameterStrategy(Type type, Optional<Class<?>> parametrizableClass) {
    DetailFieldStrategy strategy = null;
    // es un tipo generico y tengo que obtener la info de la clasex
    Optional<Type> genericType = Optional.empty();
    if (parametrizableClass.isPresent())
        genericType = ReflectionUtils.getRealType(type, parametrizableClass.get());

    LOGGER.debug("Clase generica : {}, para la clase:{}, del tipo: {}", parametrizableClass.orElse(null),
            genericType, type);
    // si la clase contenedora del parametro es collection
    if (Iterable.class.isAssignableFrom(ReflectionUtils.getClass(type).orElse(null))) {
        if (parametrizableClass.isPresent()) {
            strategy = new CollectionStrategy(genericType.orElse(null));
        } else {
            strategy = new ModelStrategy(genericType.orElse(null));
        }
    } else {
        strategy = new ModelStrategy(genericType.orElse(null));
    }
    return strategy;
}
项目:gitplex-mit    文件:ReflectionUtils.java   
/**
 * Get the underlying class for a type.
 * <p>
 * @param type
 *          the type to get class from
 * @return 
 *          the underlying class, or <tt>null</tt> if the type is a variable type
 */
private static Class<?> getClass(Type type) {
    if (type instanceof Class) {
        return (Class<?>) type;
    } else if (type instanceof ParameterizedType) {
        return getClass(((ParameterizedType) type).getRawType());
    } else if (type instanceof GenericArrayType) {
        Type componentType = ((GenericArrayType) type)
                .getGenericComponentType();
        Class<?> componentClass = getClass(componentType);
        if (componentClass != null) {
            return Array.newInstance(componentClass, 0).getClass();
        } else {
            return null;
        }
    } else {
        return null;
    }
}
项目:OftenPorter    文件:Porter.java   
private void initSuperGenericClasses() throws Exception
{

    Type superclassType = clazz.getGenericSuperclass();
    if (!ParameterizedType.class.isAssignableFrom(superclassType.getClass()))
    {
        return;
    }

    List<Class> list = new ArrayList<>();

    Type[] types = ((ParameterizedType) superclassType).getActualTypeArguments();
    ClassLoader classLoader = autoSetHandle.getInnerContextBridge().classLoader;
    for (Type type : types)
    {
        String className = getClassName(type);
        if (className == null)
        {
            continue;
        }
        list.add(PackageUtil.newClass(className, classLoader));
    }
    superGenericClasses = list.toArray(new Class[0]);
}
项目:GitHub    文件:GsonMessageBodyProvider.java   
@Override
public Object readFrom(
    Class<Object> type,
    Type genericType,
    Annotation[] annotations,
    MediaType mediaType,
    MultivaluedMap<String, String> httpHeaders,
    InputStream entityStream)
    throws IOException,
      WebApplicationException {
  try {
    return streamer.read(gson, genericType, entityStream);
  } catch (IOException ex) {
    exceptionHandler.onRead(gson, ex);
    throw ex;
  }
}
项目:GitHub    文件:ScalaCallAdapterFactoryTest.java   
@Test public void responseType() {
  Type bodyClass = new TypeToken<Future<String>>() {}.getType();
  assertThat(factory.get(bodyClass, NO_ANNOTATIONS, retrofit).responseType())
      .isEqualTo(String.class);
  Type bodyWildcard = new TypeToken<Future<? extends String>>() {}.getType();
  assertThat(factory.get(bodyWildcard, NO_ANNOTATIONS, retrofit).responseType())
      .isEqualTo(String.class);
  Type bodyGeneric = new TypeToken<Future<List<String>>>() {}.getType();
  assertThat(factory.get(bodyGeneric, NO_ANNOTATIONS, retrofit).responseType())
      .isEqualTo(new TypeToken<List<String>>() {}.getType());
  Type responseClass = new TypeToken<Future<Response<String>>>() {}.getType();
  assertThat(factory.get(responseClass, NO_ANNOTATIONS, retrofit).responseType())
      .isEqualTo(String.class);
  Type responseWildcard = new TypeToken<Future<Response<? extends String>>>() {}.getType();
  assertThat(factory.get(responseWildcard, NO_ANNOTATIONS, retrofit).responseType())
      .isEqualTo(String.class);
  Type resultClass = new TypeToken<Future<Response<String>>>() {}.getType();
  assertThat(factory.get(resultClass, NO_ANNOTATIONS, retrofit).responseType())
      .isEqualTo(String.class);
  Type resultWildcard = new TypeToken<Future<Response<? extends String>>>() {}.getType();
  assertThat(factory.get(resultWildcard, NO_ANNOTATIONS, retrofit).responseType())
      .isEqualTo(String.class);
}
项目:crnk-framework    文件:ExceptionMapperRegistryBuilder.java   
private Class<? extends Throwable> getGenericType(Class<? extends JsonApiExceptionMapper> mapper) {
    Type[] types = mapper.getGenericInterfaces();
    if (null == types || 0 == types.length) {
        types = new Type[]{mapper.getGenericSuperclass()};
    }

    for (Type type : types) {
        Class<?> rawType = ClassUtils.getRawType(type);
        if (type instanceof ParameterizedType && JsonApiExceptionMapper.class.isAssignableFrom(rawType))
        {
            //noinspection unchecked
            return (Class<? extends Throwable>) ((ParameterizedType) type).getActualTypeArguments()[0];
        }
    }

    if(isProxy(mapper)){
        return getGenericType((Class<? extends JsonApiExceptionMapper>) mapper.getSuperclass());
    }

    //Won't get in here
    throw new IllegalStateException("unable to discover exception class for " + mapper.getName());
}
项目:jsouplib    文件:TypeLiteral.java   
private static String formatTypeWithoutSpecialCharacter(Type type) {
    if (type instanceof Class) {
        Class clazz = (Class) type;
        return clazz.getCanonicalName();
    }
    if (type instanceof ParameterizedType) {
        ParameterizedType pType = (ParameterizedType) type;
        String typeName = formatTypeWithoutSpecialCharacter(pType.getRawType());
        for (Type typeArg : pType.getActualTypeArguments()) {
            typeName += "_";
            typeName += formatTypeWithoutSpecialCharacter(typeArg);
        }
        return typeName;
    }
    if (type instanceof GenericArrayType) {
        GenericArrayType gaType = (GenericArrayType) type;
        return formatTypeWithoutSpecialCharacter(gaType.getGenericComponentType()) + "_array";
    }
    throw new AJsoupReaderException("unsupported type: " + type + ", of class " + type.getClass());
}
项目:XSnow    文件:UploadRequest.java   
@Override
protected <T> Observable<T> execute(Type type) {
    if (stringBuilder.length() > 0) {
        suffixUrl = suffixUrl + stringBuilder.toString();
    }
    if (params != null && params.size() > 0) {
        Iterator<Map.Entry<String, String>> entryIterator = params.entrySet().iterator();
        Map.Entry<String, String> entry;
        while (entryIterator.hasNext()) {
            entry = entryIterator.next();
            if (entry != null) {
                multipartBodyParts.add(MultipartBody.Part.createFormData(entry.getKey(), entry.getValue()));
            }
        }
    }
    return apiService.uploadFiles(suffixUrl, multipartBodyParts).compose(this.<T>norTransformer(type));
}
项目:GitHub    文件:RetrofitTest.java   
@Test public void responseConverterFactoryQueried() {
  Type type = String.class;
  Annotation[] annotations = new Annotation[0];

  Converter<ResponseBody, ?> expectedAdapter = mock(Converter.class);
  Converter.Factory factory = mock(Converter.Factory.class);

  Retrofit retrofit = new Retrofit.Builder()
      .baseUrl("http://example.com/")
      .addConverterFactory(factory)
      .build();

  doReturn(expectedAdapter).when(factory).responseBodyConverter(type, annotations, retrofit);

  Converter<ResponseBody, ?> actualAdapter = retrofit.responseBodyConverter(type, annotations);
  assertThat(actualAdapter).isSameAs(expectedAdapter);

  verify(factory).responseBodyConverter(type, annotations, retrofit);
  verifyNoMoreInteractions(factory);
}
项目:AppleSeed    文件:IndexTypeLookup.java   
/**
 * Given a type, infer the {@link IndexType} that is used to store and query a field.
 *
 * @param type
 * @return
 */
protected IndexType inferIndexType(Type type) {
    // we go a direct get first
    IndexType indexType = indexTypeMappingCache.get(type);
    if (indexType == null) {
        if (TypeIntrospector.isACollection(type)) {
            type = TypeIntrospector.getCollectionType(type);
        }
        Class<?> classType = TypeIntrospector.asClass(type);
        // if not present, we find the first match in the cache
        for (Map.Entry<Class<?>, IndexType> entry : indexTypeMappingCache.entrySet()) {
            if (entry.getKey().isAssignableFrom(classType)) {
                indexType = entry.getValue();
                // put the matching type back into the cache to speed up subsequent inference
                indexTypeMappingCache.put(classType, indexType);
                break;
            }
        }
    }
    if (indexType == null) {
        throw new SearchException("Unable to infer an %s for the type %s - you should add a mapping using the %s", IndexTypeLookup.class.getSimpleName(), type,
                IndexTypeLookup.class.getSimpleName());
    }
    return indexType;
}
项目:CustomWorldGen    文件:ConfigManager.java   
public static void loadData(ASMDataTable data)
{
    FMLLog.fine("Loading @Config anotation data");
    for (ASMData target : data.getAll(Config.class.getName()))
    {
        String modid = (String)target.getAnnotationInfo().get("modid");
        Multimap<Config.Type, ASMData> map = asm_data.get(modid);
        if (map == null)
        {
            map = ArrayListMultimap.create();
            asm_data.put(modid, map);
        }

        EnumHolder tholder = (EnumHolder)target.getAnnotationInfo().get("type");
        Config.Type type = tholder == null ? Config.Type.INSTANCE : Config.Type.valueOf(tholder.getValue());

        map.put(type, target);
    }
}
项目:holon-json    文件:GsonPropertyBoxSerializer.java   
@Override
public JsonElement serialize(PropertyBox src, Type typeOfSrc, JsonSerializationContext context) {

    JsonObject obj = new JsonObject();

    for (Property<?> property : src) {
        // only model properties are serialized
        if (property instanceof Path) {
            final Object value = src.getValue(property);
            // do not serialize null values
            if (value != null) {
                obj.add(((Path<?>) property).getName(), context.serialize(value));
            }
        }
    }

    return obj;
}
项目:odoo-work    文件:TypeToken.java   
/**
 * Private helper function that performs some assignability checks for
 * the provided GenericArrayType.
 */
private static boolean isAssignableFrom(Type from, GenericArrayType to) {
  Type toGenericComponentType = to.getGenericComponentType();
  if (toGenericComponentType instanceof ParameterizedType) {
    Type t = from;
    if (from instanceof GenericArrayType) {
      t = ((GenericArrayType) from).getGenericComponentType();
    } else if (from instanceof Class<?>) {
      Class<?> classType = (Class<?>) from;
      while (classType.isArray()) {
        classType = classType.getComponentType();
      }
      t = classType;
    }
    return isAssignableFrom(t, (ParameterizedType) toGenericComponentType,
        new HashMap<String, Type>());
  }
  // No generic defined on "to"; therefore, return true and let other
  // checks determine assignability
  return true;
}
项目:incubator-servicecomb-java-chassis    文件:RestOperationMeta.java   
public void init(OperationMeta operationMeta) {
  this.operationMeta = operationMeta;

  Swagger swagger = operationMeta.getSchemaMeta().getSwagger();
  Operation operation = operationMeta.getSwaggerOperation();
  this.produces = operation.getProduces();
  if (produces == null) {
    this.produces = swagger.getProduces();
  }

  this.createProduceProcessors();

  Method method = operationMeta.getMethod();
  Type[] genericParamTypes = method.getGenericParameterTypes();
  if (genericParamTypes.length != operation.getParameters().size()) {
    throw new Error("Param count is not equal between swagger and method,  path=" + absolutePath);
  }

  // 初始化所有rest param
  for (int idx = 0; idx < genericParamTypes.length; idx++) {
    Parameter parameter = operation.getParameters().get(idx);
    Type genericParamType = genericParamTypes[idx];

    if ("formData".equals(parameter.getIn())) {
      formData = true;
    }

    RestParam param = new RestParam(idx, parameter, genericParamType);
    addParam(param);
  }

  setAbsolutePath(concatPath(swagger.getBasePath(), operationMeta.getOperationPath()));
}
项目:flow-platform    文件:YmlAdaptor.java   
/**
 * get field type
 */
private Type getClazz(Field field, Class<?> clazz) {
    Method method = getGetterMethod(field, clazz);
    if (method == null) {
        return null;
    }

    return method.getGenericReturnType();
}
项目:boohee_v5.6    文件:ReflectiveTypeAdapterFactory.java   
private Map<String, BoundField> getBoundFields(Gson context, TypeToken<?> type, Class<?> raw) {
    Map<String, BoundField> result = new LinkedHashMap();
    if (!raw.isInterface()) {
        Type declaredType = type.getType();
        while (raw != Object.class) {
            for (Field field : raw.getDeclaredFields()) {
                boolean serialize = excludeField(field, true);
                boolean deserialize = excludeField(field, false);
                if (serialize || deserialize) {
                    field.setAccessible(true);
                    BoundField boundField = createBoundField(context, field, getFieldName
                            (field), TypeToken.get(C$Gson$Types.resolve(type.getType(), raw,
                            field.getGenericType())), serialize, deserialize);
                    BoundField previous = (BoundField) result.put(boundField.name, boundField);
                    if (previous != null) {
                        throw new IllegalArgumentException(declaredType + " declares multiple" +
                                " JSON fields named " + previous.name);
                    }
                }
            }
            type = TypeToken.get(C$Gson$Types.resolve(type.getType(), raw, raw
                    .getGenericSuperclass()));
            raw = type.getRawType();
        }
    }
    return result;
}
项目:dtmlibs    文件:Field.java   
@NotNull
private Type determineActualType(@NotNull java.lang.reflect.Field field) {
    Type type = field.getGenericType();
    Class clazz = GenericTypeReflector.erase(type);
    if (VirtualField.class.isAssignableFrom(clazz)) {
        type = GenericTypeReflector.getExactSuperType(type, VirtualField.class);
        if (type instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) type;
            type = parameterizedType.getActualTypeArguments()[0];
        }
    }
    return type;
}
项目:JInOne    文件:JUtil.java   
public static <T> T fromJsonElement(JsonElement json, Type type){
    if(json!=null){
        Gson gson = new Gson();
        try {
            return gson.fromJson(json, type);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    return null;
}
项目:BaseCore    文件:GsonUtils.java   
/**
 * 将Json字符串转化为Map
 * jsonStr Json字符串
 *
 * @return String
 */
public static <T> Map<String, T> jsonStrToMap(String jsonStr) {
    Gson gson = new Gson();
    Type type = new TypeToken<Map<String, T>>() {
    }.getType();
    return gson.fromJson(jsonStr, type);
}
项目:teamcity-hashicorp-vault-plugin    文件:AbstractJackson2HttpMessageConverter.java   
@Override
public Object read(Type type, Class<?> contextClass, HttpInputMessage inputMessage)
        throws IOException, HttpMessageNotReadableException {

    JavaType javaType = getJavaType(type, contextClass);
    return readJavaType(javaType, inputMessage);
}
项目:config    文件:ObjectPropertyField.java   
private boolean isMultimap(ParameterizedType paramType) {
  boolean result = false;
  if (paramType.getRawType() == Map.class) {
    Type[] typeArguments = paramType.getActualTypeArguments();
    Type keyType = typeArguments[0];
    Type valueType = typeArguments[1];
    if (keyType == String.class && valueType instanceof ParameterizedType) {
      ParameterizedType parameterizedValueType = ((ParameterizedType) valueType);
      if (parameterizedValueType.getRawType() == List.class) {
        result = true;
      }
    }
  }
  return result;
}
项目:484_P7_1-Java    文件:RectangularTextContainerSerializer.java   
@Override
public JsonElement serialize(RectangularTextContainer<?> src, Type typeOfSrc, JsonSerializationContext context) {
    JsonObject result = new JsonObject();
    result.addProperty("top",    src.getTop());
    result.addProperty("left",   src.getLeft());
    result.addProperty("width",  src.getWidth());
    result.addProperty("height", src.getHeight());
    result.addProperty("text",   src.getText());
    return result;
}
项目:GitHub    文件:StringConverterFactory.java   
@Override public Converter<?, RequestBody> requestBodyConverter(Type type,
    Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
  return new Converter<String, RequestBody>() {
    @Override public RequestBody convert(String value) throws IOException {
      return RequestBody.create(MediaType.parse("text/plain"), value);
    }
  };
}
项目:openjdk-jdk10    文件:ParameterizedTypeImpl.java   
public String toString() {
    StringBuilder sb = new StringBuilder();

    if (ownerType != null) {
        if (ownerType instanceof Class)
            sb.append(((Class) ownerType).getName());
        else
            sb.append(ownerType.toString());

        sb.append(".");

        if (ownerType instanceof ParameterizedTypeImpl) {
            // Find simple name of nested type by removing the
            // shared prefix with owner.
            sb.append(rawType.getName().replace(((ParameterizedTypeImpl) ownerType).rawType.getName() + "$",
                    ""));
        } else
            sb.append(rawType.getName());
    } else
        sb.append(rawType.getName());

    if (actualTypeArguments != null &&
            actualTypeArguments.length > 0) {
        sb.append("<");
        boolean first = true;
        for (Type t : actualTypeArguments) {
            if (!first)
                sb.append(", ");
            if (t instanceof Class)
                sb.append(((Class) t).getName());
            else
                sb.append(t.toString());
            first = false;
        }
        sb.append(">");
    }

    return sb.toString();
}
项目:inspector    文件:ClassValidator.java   
@Override public @Nullable Validator<?> create(Type type,
    Set<? extends Annotation> annotations,
    Inspector inspector) {
  Class<?> rawType = Types.getRawType(type);
  if (rawType.isInterface() || rawType.isEnum()) return null;
  if (isPlatformType(rawType) && !Types.isAllowedPlatformType(rawType)) {
    throw new IllegalArgumentException("Platform "
        + type
        + " annotated "
        + annotations
        + " requires explicit Validator to be registered");
  }
  if (!annotations.isEmpty()) return null;

  if (rawType.getEnclosingClass() != null && !Modifier.isStatic(rawType.getModifiers())) {
    if (rawType.getSimpleName()
        .isEmpty()) {
      throw new IllegalArgumentException("Cannot validate anonymous class "
          + rawType.getName());
    } else {
      throw new IllegalArgumentException("Cannot validate non-static nested class "
          + rawType.getName());
    }
  }
  if (Modifier.isAbstract(rawType.getModifiers())) {
    throw new IllegalArgumentException("Cannot validate abstract class " + rawType.getName());
  }

  ClassFactory<Object> classFactory = ClassFactory.get(rawType);
  Map<String, MethodBinding<?>> methods = new TreeMap<>();
  for (Type t = type; t != Object.class; t = Types.getGenericSuperclass(t)) {
    createMethodBindings(inspector, t, methods);
  }
  return new ClassValidator<>(classFactory, methods).nullSafe();
}
项目:GitHub    文件:BraveNewGenericsTest.java   
@Test
public void customGenerics() {
  Type t = new TypeToken<Botts<Integer>>() {}.getType();
  Botts<Integer> t1 = CustomGenerics.createBotts();
  String json = gson.toJson(t1, t);
  Botts<Integer> t2 = gson.fromJson(json, t);
  check(t2).is(t1);
}
项目:ucar-weex-core    文件:WXReflectionUtils.java   
public static Object parseArgument(Type paramClazz, Object value) {
  if (paramClazz == String.class) {
    return value instanceof String ? value : JSON.toJSONString(value);
  } else if (paramClazz == int.class) {
    return value.getClass().isAssignableFrom(int.class) ? value : WXUtils.getInt(value);
  } else if (paramClazz == long.class) {
    return value.getClass().isAssignableFrom(long.class) ? value : WXUtils.getLong(value);
  } else if (paramClazz == double.class) {
    return value.getClass().isAssignableFrom(double.class) ? value : WXUtils.getDouble(value);
  } else if (paramClazz == float.class) {
    return value.getClass().isAssignableFrom(float.class) ? value : WXUtils.getFloat(value);
  } else {
    return JSON.parseObject(value instanceof String ? (String) value : JSON.toJSONString(value), paramClazz);
  }
}
项目:DeepImagePreview-Project    文件:TextClassifierTest.java   
@Test
public void testGivenSampleDataWhenPredictThenCorrectResultReturned() throws Exception {

    // Load test data
    Type type = new TypeToken<ArrayList<FoodTestEntry>>() {
    }.getType();
    Resources resources = InstrumentationRegistry.getContext().getResources();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(resources.getAssets().open("sample_classifier_test_data.json")));
    ArrayList<FoodTestEntry> foodTestEntries = new Gson().fromJson(bufferedReader, type);

    int failed = 0;

    // Predict and test
    for (FoodTestEntry foodTestEntry : foodTestEntries) {
        String textToPredict = foodTestEntry.getText();
        boolean isPredictionCorrect = mCut.isFoodRelated(textToPredict) == foodTestEntry.isFood();

        if (isPredictionCorrect) {
            System.out.println("SUCCESS Predicted [" + textToPredict + "] correctly!");
        } else {
            failed++;
            System.out.println("FAILED Predicted [" + textToPredict + "], expecting [" + foodTestEntry.isFood() + "] but was [" + mCut
                    .isFoodRelated(textToPredict) + "]");
        }
    }

    if (failed > 0) {

        int totalTestSize = foodTestEntries.size();
        float failedPerc = (float) failed * totalTestSize / 100f;

        fail(failed + " out of " + totalTestSize + " failed [" + failedPerc + "%]");
    }
}
项目:AlphaLibary    文件:JSONUtil.java   
public GameProfile deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException {
    JsonObject object = (JsonObject) json;
    UUID id = object.has("id") ? (UUID) context.deserialize(object.get("id"), UUID.class) : null;
    String name = object.has("name") ? object.getAsJsonPrimitive("name").getAsString() : null;
    GameProfile profile = new GameProfile(id, name);

    if (object.has("properties")) {
        for (Map.Entry<String, Property> prop : ((PropertyMap) context.deserialize(object.get("properties"), PropertyMap.class)).entries()) {
            profile.getProperties().put(prop.getKey(), prop.getValue());
        }
    }
    return profile;
}
项目:RestyPass    文件:JsonResponseConverter.java   
@Override
public Object convert(byte[] body, Type type, String contentType) {
    JavaType javaType = TypeFactory.defaultInstance().constructType(type);
    try {
        return objectMapper.readValue(body, javaType);
    } catch (IOException e) {
        log.error("JSON转换失败,javaType:{}", javaType, e);
    }
    return null;
}
项目:openjdk-jdk10    文件:ConstructorRepository.java   
public Type[] getParameterTypes() {
    Type[] value = parameterTypes;
    if (value == null) {
        value = computeParameterTypes();
        parameterTypes = value;
    }
    return value.clone();
}
项目:guava-mock    文件:TypeToken.java   
/**
 * Returns true if this type is a subtype of the given {@code type}. "Subtype" is defined
 * according to
 * <a href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.5.1">the rules for
 * type arguments</a> introduced with Java generics.
 *
 * @since 19.0
 */
public final boolean isSubtypeOf(Type supertype) {
  checkNotNull(supertype);
  if (supertype instanceof WildcardType) {
    // if 'supertype' is <? super Foo>, 'this' can be:
    // Foo, SubFoo, <? extends Foo>.
    // if 'supertype' is <? extends Foo>, nothing is a subtype.
    return any(((WildcardType) supertype).getLowerBounds()).isSupertypeOf(runtimeType);
  }
  // if 'this' is wildcard, it's a suptype of to 'supertype' if any of its "extends"
  // bounds is a subtype of 'supertype'.
  if (runtimeType instanceof WildcardType) {
    // <? super Base> is of no use in checking 'from' being a subtype of 'to'.
    return any(((WildcardType) runtimeType).getUpperBounds()).isSubtypeOf(supertype);
  }
  // if 'this' is type variable, it's a subtype if any of its "extends"
  // bounds is a subtype of 'supertype'.
  if (runtimeType instanceof TypeVariable) {
    return runtimeType.equals(supertype)
        || any(((TypeVariable<?>) runtimeType).getBounds()).isSubtypeOf(supertype);
  }
  if (runtimeType instanceof GenericArrayType) {
    return of(supertype).isSupertypeOfArray((GenericArrayType) runtimeType);
  }
  // Proceed to regular Type subtype check
  if (supertype instanceof Class) {
    return this.someRawTypeIsSubclassOf((Class<?>) supertype);
  } else if (supertype instanceof ParameterizedType) {
    return this.isSubtypeOfParameterizedType((ParameterizedType) supertype);
  } else if (supertype instanceof GenericArrayType) {
    return this.isSubtypeOfArrayType((GenericArrayType) supertype);
  } else { // to instanceof TypeVariable
    return false;
  }
}
项目:uavstack    文件:FileCodec.java   
public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
    SerializeWriter out = serializer.getWriter();

    if (object == null) {
        out.writeNull();
        return;
    }

    File file = (File) object;

    serializer.write(file.getPath());
}
项目:lemon    文件:GenericsUtils.java   
/**
 * 通过反射,获得定义Class时声明的父类的范型参数的类型. 如public BookManager extends GenricManager&lt;Book&gt;
 * 
 * @param clazz
 *            clazz The class to introspect
 * @param index
 *            the Index of the generic ddeclaration,start from 0.
 * @return the index generic declaration, or <code>Object.class</code> if cannot be determined
 */
public static Class getSuperClassGenericType(Class clazz, int index) {
    Type genType = clazz.getGenericSuperclass();

    if (clazz.getSimpleName().indexOf("$$EnhancerByCGLIB$$") != -1) {
        genType = ((Class) genType).getGenericSuperclass();
    }

    if (!(genType instanceof ParameterizedType)) {
        logger.warn("{}'s superclass not ParameterizedType",
                clazz.getSimpleName());

        return Object.class;
    }

    Type[] params = ((ParameterizedType) genType).getActualTypeArguments();

    if ((index >= params.length) || (index < 0)) {
        logger.warn(
                "Index: {}, Size of {}'s Parameterized Type: {}",
                new Object[] { index, clazz.getSimpleName(), params.length });

        return Object.class;
    }

    if (!(params[index] instanceof Class)) {
        logger.warn(
                "{} not set the actual class on superclass generic parameter",
                clazz.getSimpleName());

        return Object.class;
    }

    return (Class) params[index];
}
项目:mapbox-events-android    文件:FeedbackEventDataSerializer.java   
@Override
public JsonElement serialize(FeedbackEventData src, Type typeOfSrc, JsonSerializationContext context) {
  JsonObject feedbackEventData = new JsonObject();
  feedbackEventData.addProperty(FEEDBACK_TYPE, src.getFeedbackType());
  feedbackEventData.addProperty(DESCRIPTION, src.getDescription());
  feedbackEventData.addProperty(SOURCE, src.getSource());
  feedbackEventData.addProperty(USER_ID, src.getUserId());
  feedbackEventData.addProperty(AUDIO, src.getAudio());
  return feedbackEventData;
}
项目:OneClient    文件:JsonUtil.java   
@Override
public JsonElement serialize(ModInstaller src, Type typeOfSrc, JsonSerializationContext context) {
    JsonObject object = new JsonObject();
    object.addProperty("name", src.getName());
    object.addProperty("type", src.getType().name());
    object.add("hash", GSON.toJsonTree(src.getHash()));
    if (src instanceof CurseModInstaller) {
        object.add("data", GSON.toJsonTree(((CurseModInstaller) src).getFileData()));
    }
    return object;
}