Java Code Examples for java.lang.reflect.Type

The following are top voted examples for showing how to use java.lang.reflect.Type. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: bubichain-sdk-java   File: TypeUtils.java   Source Code and License 8 votes vote down vote up
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;
}
 
Example 2
Project: ditb   File: ProtobufUtil.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
}
 
Example 3
Project: Wechat-Group   File: WxMpMaterialNewsBatchGetGsonAdapter.java   Source Code and License 6 votes vote down vote up
@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;
}
 
Example 4
Project: thrifty-retrofit-converter   File: ThriftyConverterFactory.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 5
Project: spring-rest-commons-options   File: DetailFieldCreatedStrategyFactory.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 6
Project: gitplex-mit   File: ReflectionUtils.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
	}
}
 
Example 7
Project: OftenPorter   File: Porter.java   Source Code and License 6 votes vote down vote up
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]);
}
 
Example 8
Project: GitHub   File: GsonMessageBodyProvider.java   Source Code and License 6 votes vote down vote up
@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;
  }
}
 
Example 9
Project: GitHub   File: ScalaCallAdapterFactoryTest.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 10
Project: crnk-framework   File: ExceptionMapperRegistryBuilder.java   Source Code and License 6 votes vote down vote up
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());
}
 
Example 11
Project: jsouplib   File: TypeLiteral.java   Source Code and License 6 votes vote down vote up
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());
}
 
Example 12
Project: XSnow   File: UploadRequest.java   Source Code and License 6 votes vote down vote up
@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));
}
 
Example 13
Project: GitHub   File: RetrofitTest.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 14
Project: Phoenix-for-VK   File: CommentDtoAdapter.java   Source Code and License 6 votes vote down vote up
@Override
public VKApiComment deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    JsonObject root = json.getAsJsonObject();
    VKApiComment dto = new VKApiComment();

    dto.id = optInt(root, "id");
    dto.from_id = optInt(root, "from_id");

    if(dto.from_id == 0){
        dto.from_id = optInt(root, "owner_id");
    }

    dto.date = optLong(root, "date");
    dto.text = optString(root, "text");
    dto.reply_to_user = optInt(root, "reply_to_user");
    dto.reply_to_comment = optInt(root, "reply_to_comment");

    if(root.has("attachments")){
        dto.attachments = context.deserialize(root.get("attachments"), VkApiAttachments.class);
    }

    if(root.has("likes")){
        JsonObject likesRoot = root.getAsJsonObject("likes");
        dto.likes = optInt(likesRoot, "count");
        dto.user_likes = optIntAsBoolean(likesRoot, "user_likes");
        dto.can_like = optIntAsBoolean(likesRoot, "can_like");
    }

    dto.can_edit = optIntAsBoolean(root, "can_edit");
    return dto;
}
 
Example 15
Project: AppleSeed   File: IndexTypeLookup.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
}
 
Example 16
Project: CustomWorldGen   File: ConfigManager.java   Source Code and License 6 votes vote down vote up
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);
    }
}
 
Example 17
Project: holon-json   File: GsonPropertyBoxSerializer.java   Source Code and License 6 votes vote down vote up
@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;
}
 
Example 18
Project: odoo-work   File: TypeToken.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
}
 
Example 19
Project: incubator-servicecomb-java-chassis   File: RestOperationMeta.java   Source Code and License 5 votes vote down vote up
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()));
}
 
Example 20
Project: flow-platform   File: YmlAdaptor.java   Source Code and License 5 votes vote down vote up
/**
 * get field type
 */
private Type getClazz(Field field, Class<?> clazz) {
    Method method = getGetterMethod(field, clazz);
    if (method == null) {
        return null;
    }

    return method.getGenericReturnType();
}
 
Example 21
Project: boohee_v5.6   File: ReflectiveTypeAdapterFactory.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 22
Project: dtmlibs   File: Field.java   Source Code and License 5 votes vote down vote up
@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;
}
 
Example 23
Project: JInOne   File: JUtil.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 24
Project: BaseCore   File: GsonUtils.java   Source Code and License 5 votes vote down vote up
/**
 * 将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);
}
 
Example 25
Project: teamcity-hashicorp-vault-plugin   File: AbstractJackson2HttpMessageConverter.java   Source Code and License 5 votes vote down vote up
@Override
public Object read(Type type, Class<?> contextClass, HttpInputMessage inputMessage)
		throws IOException, HttpMessageNotReadableException {

	JavaType javaType = getJavaType(type, contextClass);
	return readJavaType(javaType, inputMessage);
}
 
Example 26
Project: config   File: ObjectPropertyField.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 27
Project: 484_P7_1-Java   File: RectangularTextContainerSerializer.java   Source Code and License 5 votes vote down vote up
@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;
}
 
Example 28
Project: GitHub   File: StringConverterFactory.java   Source Code and License 5 votes vote down vote up
@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);
    }
  };
}
 
Example 29
Project: openjdk-jdk10   File: ParameterizedTypeImpl.java   Source Code and License 5 votes vote down vote up
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();
}
 
Example 30
Project: inspector   File: ClassValidator.java   Source Code and License 5 votes vote down vote up
@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();
}
 
Example 31
Project: GitHub   File: BraveNewGenericsTest.java   Source Code and License 5 votes vote down vote up
@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);
}
 
Example 32
Project: ucar-weex-core   File: WXReflectionUtils.java   Source Code and License 5 votes vote down vote up
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);
  }
}
 
Example 33
Project: DeepImagePreview-Project   File: TextClassifierTest.java   Source Code and License 5 votes vote down vote up
@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 + "%]");
    }
}
 
Example 34
Project: AlphaLibary   File: JSONUtil.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 35
Project: RestyPass   File: JsonResponseConverter.java   Source Code and License 5 votes vote down vote up
@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;
}
 
Example 36
Project: openjdk-jdk10   File: ConstructorRepository.java   Source Code and License 5 votes vote down vote up
public Type[] getParameterTypes() {
    Type[] value = parameterTypes;
    if (value == null) {
        value = computeParameterTypes();
        parameterTypes = value;
    }
    return value.clone();
}
 
Example 37
Project: guava-mock   File: TypeToken.java   Source Code and License 5 votes vote down vote up
/**
 * 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;
  }
}
 
Example 38
Project: uavstack   File: FileCodec.java   Source Code and License 5 votes vote down vote up
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());
}
 
Example 39
Project: lemon   File: GenericsUtils.java   Source Code and License 5 votes vote down vote up
/**
 * 通过反射,获得定义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];
}
 
Example 40
Project: mapbox-events-android   File: FeedbackEventDataSerializer.java   Source Code and License 5 votes vote down vote up
@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;
}
 
Example 41
Project: OneClient   File: JsonUtil.java   Source Code and License 5 votes vote down vote up
@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;
}
 
Example 42
Project: rxjava2_retrofit2   File: StringConverterFactory.java   Source Code and License 5 votes vote down vote up
@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {

    if (!String.class.equals(type)) {
        return null;
    }
    return new StringResponseBodyConverter();
}
 
Example 43
Project: nifi-swagger-client   File: ProcessGroupsApi.java   Source Code and License 5 votes vote down vote up
/**
 * Creates a funnel (asynchronously)
 * 
 * @param id The process group id. (required)
 * @param body The funnel configuration details. (required)
 * @param callback The callback to be executed when the API call finishes
 * @return The request call
 * @throws ApiException If fail to process the API call, e.g. serializing the request body object
 */
public com.squareup.okhttp.Call createFunnelAsync(String id, FunnelEntity body, final ApiCallback<FunnelEntity> callback) throws ApiException {

    ProgressResponseBody.ProgressListener progressListener = null;
    ProgressRequestBody.ProgressRequestListener progressRequestListener = null;

    if (callback != null) {
        progressListener = new ProgressResponseBody.ProgressListener() {
            @Override
            public void update(long bytesRead, long contentLength, boolean done) {
                callback.onDownloadProgress(bytesRead, contentLength, done);
            }
        };

        progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
            @Override
            public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
                callback.onUploadProgress(bytesWritten, contentLength, done);
            }
        };
    }

    com.squareup.okhttp.Call call = createFunnelValidateBeforeCall(id, body, progressListener, progressRequestListener);
    Type localVarReturnType = new TypeToken<FunnelEntity>(){}.getType();
    apiClient.executeAsync(call, localVarReturnType, callback);
    return call;
}
 
Example 44
Project: javadoc2swagger   File: DefinitionParser.java   Source Code and License 5 votes vote down vote up
/**
 * Processes all fields of a class
 * 
 * @param fields
 *            array of fields
 * @param definition
 *            current definition
 * @param rootDefinition
 *            definition where the recursion started to prevent an endless
 *            loop
 * @return list of {@link Property} objects
 * @throws ParserException
 *             Error while the parsing process
 */
public List<Property> processFields(Field[] fields, Definition definition, Definition rootDefinition)
        throws ParserException {
    DataTypeFactory typeHandler = new DataTypeFactory();
    List<Property> properties = new ArrayList<>();
    for (Field field : fields) {
        if (field.getAnnotation(JsonIgnore.class) == null && field.getAnnotation(JsonBackReference.class) == null) {
            Property property = new Property();
            Class<?> typeClass = field.getType();
            Annotation[] annotations = field.getAnnotations();
            Type genericType = field.getGenericType();
            processGenerics(genericType, property, definition, rootDefinition);
            DataType typeObject = typeHandler.getDataType(typeClass.getName());
            String type = typeObject.getType();
            String name = field.getName();
            property.setName(name);
            if (type.length() > 14 && (type.substring(14).equals(definition.getClassName())
                    || type.substring(14).equals(rootDefinition.getClassName()))) {
                property.setReference(type);
            } else if (type.startsWith("#")) {
                createDefinitionBySchemaAndPackageIfNotExists(type, typeClass.getTypeName(), rootDefinition);
                property.setReference(type);
            } else {
                property.setType(type);
                property.setFormat(typeObject.getFormat());
            }
            properties.add(property);
            processAnnotations(annotations, definition, name);
        }
    }
    return properties;
}
 
Example 45
Project: jTelegramBotAPI   File: InputFile.java   Source Code and License 5 votes vote down vote up
@Override
public JsonElement serialize(InputFile inputFile, Type type, JsonSerializationContext context) {
    if (inputFile instanceof LocalInputFile) {
        return new JsonPrimitive("attach://" + ((File) inputFile.getData()).getName());
    }

    return new JsonPrimitive(inputFile.getData().toString());
}
 
Example 46
Project: pact-spring-mvc   File: JacksonStringConverter.java   Source Code and License 5 votes vote down vote up
@Override
public <T> T fromString(String message, Type type) {
    try {
        return objectMapper.readValue(message.getBytes(), objectMapper.getTypeFactory().constructType(type));
    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    }
}
 
Example 47
Project: mazes_and_minotaurs   File: CharacterSerializer.java   Source Code and License 5 votes vote down vote up
@Override
public JsonElement serialize(PlayerCharacter src, Type typeOfSrc, JsonSerializationContext context) {
    BaseClass characterClass = src.getCharClass();
    characterClass.setCharacter(null);

    Type equipListType = new TypeToken<ArrayList<Equipment>>() {
    }.getType();
    Type moneyMapType = new TypeToken<HashMap<Money, Integer>>() {
    }.getType();

    JsonObject rootObject = new JsonObject();
    rootObject.add("mScores", context.serialize(src.getScores()));
    rootObject.add("mCharClass", context.serialize(src.getCharClass(), BaseClass.class));
    rootObject.add("mGender", context.serialize(src.getGender()));
    rootObject.add("mMoney", context.serialize(src.getMoney(), moneyMapType));
    rootObject.add("mAge", context.serialize(src.getAge()));
    rootObject.add("mName", context.serialize(src.getName()));
    System.out.println(getGson().toJsonTree(src.getInventory(), equipListType));
    rootObject.add("mInventory", getGson().toJsonTree(src.getInventory(), equipListType));
    rootObject.add("mCurrentWeapon", context.serialize(src.getCurrentWeapon()));
    rootObject.add("mHelmet", context.serialize(src.getHelmet()));
    rootObject.add("mBreastplate", context.serialize(src.getBreastplate()));
    rootObject.add("mShield", context.serialize(src.getShield()));
    rootObject.add("mPatron", context.serialize(src.getPatron()));

    JsonElement classJson = context.serialize(characterClass);
    rootObject.add("mCharClass", classJson);

    characterClass.setCharacter(src);
    return rootObject;
}
 
Example 48
Project: buckaroo   File: RecipeDeserializer.java   Source Code and License 5 votes vote down vote up
@Override
public Recipe deserialize(final JsonElement jsonElement, final Type type, final JsonDeserializationContext context) throws JsonParseException {

    Preconditions.checkNotNull(jsonElement);
    Preconditions.checkNotNull(type);
    Preconditions.checkNotNull(context);

    final JsonObject jsonObject = jsonElement.getAsJsonObject();

    if (!jsonObject.has("name")) {
        throw new JsonParseException("Recipes must have a name element. ");
    }
    final String name = jsonObject.get("name").getAsString();

    if (!jsonObject.has("url")) {
        throw new JsonParseException("Recipes must have a url element. ");
    }
    final URI url = context.deserialize(jsonObject.get("url"), URI.class);

    final JsonObject jsonObjectVersions = jsonObject.get("versions").getAsJsonObject();

    final ImmutableMap<SemanticVersion, RecipeVersion> versions = ImmutableMap.copyOf(
        jsonObjectVersions.entrySet().stream().collect(Collectors.toMap(
            x -> context.deserialize(new JsonPrimitive(x.getKey()), SemanticVersion.class),
            x -> context.deserialize(x.getValue(), RecipeVersion.class))));

    return Recipe.of(name, url, versions);
}
 
Example 49
Project: Android-app   File: ReleaseDateDeserializer.java   Source Code and License 5 votes vote down vote up
@Override
public ReleaseDate deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    ReleaseDate releaseDate = null;

    try{
        releaseDate = new ReleaseDate(tmdbReleaseDateFormat.parse(json.getAsString()));
    }
    catch (Exception e){
        e.printStackTrace();
    }

    return releaseDate;
}
 
Example 50
Project: swaggy-jenkins   File: BlueOceanApi.java   Source Code and License 5 votes vote down vote up
/**
 *  (asynchronously)
 * Get log for a pipeline run
 * @param organization Name of the organization (required)
 * @param pipeline Name of the pipeline (required)
 * @param run Name of the run (required)
 * @param start Start position of the log (optional)
 * @param download Set to true in order to download the file, otherwise it&#39;s passed as a response body (optional)
 * @param callback The callback to be executed when the API call finishes
 * @return The request call
 * @throws ApiException If fail to process the API call, e.g. serializing the request body object
 */
public com.squareup.okhttp.Call getPipelineRunLogAsync(String organization, String pipeline, String run, Integer start, Boolean download, final ApiCallback<String> callback) throws ApiException {

    ProgressResponseBody.ProgressListener progressListener = null;
    ProgressRequestBody.ProgressRequestListener progressRequestListener = null;

    if (callback != null) {
        progressListener = new ProgressResponseBody.ProgressListener() {
            @Override
            public void update(long bytesRead, long contentLength, boolean done) {
                callback.onDownloadProgress(bytesRead, contentLength, done);
            }
        };

        progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
            @Override
            public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
                callback.onUploadProgress(bytesWritten, contentLength, done);
            }
        };
    }

    com.squareup.okhttp.Call call = getPipelineRunLogValidateBeforeCall(organization, pipeline, run, start, download, progressListener, progressRequestListener);
    Type localVarReturnType = new TypeToken<String>(){}.getType();
    apiClient.executeAsync(call, localVarReturnType, callback);
    return call;
}
 
Example 51
Project: Wechat-Group   File: WxMpMaterialNewsGsonAdapter.java   Source Code and License 5 votes vote down vote up
@Override
public WxMpMaterialNews deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
  WxMpMaterialNews wxMpMaterialNews = new WxMpMaterialNews();
  JsonObject json = jsonElement.getAsJsonObject();
  if (json.get("news_item") != null && !json.get("news_item").isJsonNull()) {
    JsonArray articles = json.getAsJsonArray("news_item");
    for (JsonElement article1 : articles) {
      JsonObject articleInfo = article1.getAsJsonObject();
      WxMpMaterialNews.WxMpMaterialNewsArticle article = WxMpGsonBuilder.create().fromJson(articleInfo, WxMpMaterialNews.WxMpMaterialNewsArticle.class);
      wxMpMaterialNews.addArticle(article);
    }
  }
  return wxMpMaterialNews;
}
 
Example 52
Project: rockscript   File: PolymorphicTypeAdapterFactory.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
  // TODO check if GSON does caching of the created TypeAdapter for the given type

  // extra caching could be added in this layer if there is only one polymorphic type
  // adapter for the whole hierarchy

  // https://google.github.io/gson/apidocs/com/google/gson/TypeAdapterFactory.html
  // If a factory cannot support a given type, it must return null when that type is passed to create(com.google.gson.Gson, com.google.gson.reflect.TypeToken<T>)

  if (type.getType() instanceof WildcardType) {
    WildcardType wildcardType = (WildcardType) type.getType();
    Type[] upperBounds = wildcardType.getUpperBounds();
    if (upperBounds!=null && upperBounds.length==1) {
      type = (TypeToken<T>) TypeToken.get(upperBounds[0]);
    } else {
      throw new RuntimeException("Unsupported wildcard type: "+type);
    }
  }
  if (matchingTypes.contains(type)) {
    if (typeAdapter==null) {
      typeAdapter = new PolymorphicTypeAdapter<T>(type, this, gson);
    }
    return (TypeAdapter<T>) this.typeAdapter;
  }

  return null;
}
 
Example 53
Project: XSnow   File: ApiPostRequest.java   Source Code and License 5 votes vote down vote up
@Override
protected <T> Observable<T> execute(Type type) {
    if (stringBuilder.length() > 0) {
        suffixUrl = suffixUrl + stringBuilder.toString();
    }
    if (forms != null && forms.size() > 0) {
        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) {
                    forms.put(entry.getKey(), entry.getValue());
                }
            }
        }
        return apiService.postForm(suffixUrl, forms)
                .map(new ApiResultFunc<T>(type))
                .compose(this.<T>apiTransformer());
    }
    if (requestBody != null) {
        return apiService.postBody(suffixUrl, requestBody)
                .map(new ApiResultFunc<T>(type))
                .compose(this.<T>apiTransformer());
    }
    if (content != null && mediaType != null) {
        requestBody = RequestBody.create(mediaType, content);
        return apiService.postBody(suffixUrl, requestBody)
                .map(new ApiResultFunc<T>(type))
                .compose(this.<T>apiTransformer());
    }
    return apiService.post(suffixUrl, params)
            .map(new ApiResultFunc<T>(type))
            .compose(this.<T>apiTransformer());
}
 
Example 54
Project: RxEasyHttp   File: AppConstant.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) {
    String json = "{\n" +
            "    \"data\": 1468993603787,\n" +
            "    \"code\": 100010104,\n" +
            "    \"msg\": \"timestamp过期\"\n" +
            "}";

    Gson gson = new Gson();
    Type type = new TypeToken<Map<String, String>>() {
    }.getType();
    Map ss = gson.fromJson(json, type);
    System.out.println(ss);
}
 
Example 55
Project: skywalking-mock-collector   File: ValidateDataSerializer.java   Source Code and License 5 votes vote down vote up
@Override
public JsonElement serialize(ValidateData src, Type typeOfSrc, JsonSerializationContext context) {
    Gson gson = new GsonBuilder().registerTypeAdapter(RegistryItem.class, new RegistryItemSerializer())
        .registerTypeAdapter(SegmentItems.class, new SegmentItemsSerializer()).create();

    JsonObject jsonObject = new JsonObject();
    jsonObject.add("registryItems", gson.toJsonTree(src.getRegistryItem()));
    jsonObject.add("segmentItems", gson.toJsonTree(src.getSegmentItem()));
    return jsonObject;
}
 
Example 56
Project: knowledge-forest-dialogue-recommendation   File: JsonUtils.java   Source Code and License 5 votes vote down vote up
public static <T> ArrayList<T> jsonToArrayList(String json, Class<T> clazz) {
    Type type = new TypeToken<ArrayList<JsonObject>>() {
    }.getType();
    ArrayList<JsonObject> jsonObjects = new Gson().fromJson(json, type);

    ArrayList<T> arrayList = new ArrayList<>();
    for (JsonObject jsonObject : jsonObjects) {
        arrayList.add(new Gson().fromJson(jsonObject, clazz));
    }
    return arrayList;
}
 
Example 57
Project: BizareChat   File: QualifiedTypeConverterFactory.java   Source Code and License 5 votes vote down vote up
@Override
public Converter<?, RequestBody> requestBodyConverter(Type type,
                                                      Annotation[] parameterAnnotations,
                                                      Annotation[] methodAnnotations,
                                                      Retrofit retrofit) {
    for (Annotation annotation : methodAnnotations) {
        if (annotation instanceof JsonAndXmlConverters.Xml) {
            return xmlFactory.requestBodyConverter(type, parameterAnnotations, methodAnnotations, retrofit);
        }
    }
    return jsonFactory.requestBodyConverter(type, parameterAnnotations, methodAnnotations, retrofit);
}
 
Example 58
Project: coner-core-client-java   File: HandicapGroupsApi.java   Source Code and License 5 votes vote down vote up
/**
 * Add a Handicap Group to a Handicap Group Set (asynchronously)
 * 
 * @param handicapGroupSetId Handicap Group Set ID (required)
 * @param handicapGroupId Handicap Group ID (required)
 * @param callback The callback to be executed when the API call finishes
 * @return The request call
 * @throws ApiException If fail to process the API call, e.g. serializing the request body object
 */
public com.squareup.okhttp.Call addHandicapGroupToHandicapGroupSetAsync(String handicapGroupSetId, String handicapGroupId, final ApiCallback<HandicapGroupSetApiEntity> callback) throws ApiException {

    ProgressResponseBody.ProgressListener progressListener = null;
    ProgressRequestBody.ProgressRequestListener progressRequestListener = null;

    if (callback != null) {
        progressListener = new ProgressResponseBody.ProgressListener() {
            @Override
            public void update(long bytesRead, long contentLength, boolean done) {
                callback.onDownloadProgress(bytesRead, contentLength, done);
            }
        };

        progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
            @Override
            public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
                callback.onUploadProgress(bytesWritten, contentLength, done);
            }
        };
    }

    com.squareup.okhttp.Call call = addHandicapGroupToHandicapGroupSetValidateBeforeCall(handicapGroupSetId, handicapGroupId, progressListener, progressRequestListener);
    Type localVarReturnType = new TypeToken<HandicapGroupSetApiEntity>(){}.getType();
    apiClient.executeAsync(call, localVarReturnType, callback);
    return call;
}
 
Example 59
Project: junit5-extensions   File: GuiceExtension.java   Source Code and License 5 votes vote down vote up
private static Key<?> getKey(Optional<Class<?>> containingElement, Parameter parameter) {
  Class<?> clazz =
      containingElement.orElseGet(() -> parameter.getDeclaringExecutable().getDeclaringClass());
  TypeToken<?> classType = TypeToken.of(clazz);
  Type resolvedType = classType.resolveType(parameter.getParameterizedType()).getType();

  Optional<Key<?>> key =
      getOnlyBindingAnnotation(parameter).map(annotation -> Key.get(resolvedType, annotation));
  return key.orElse(Key.get(resolvedType));
}
 
Example 60
Project: AndroidBasicLibs   File: FieldUtil.java   Source Code and License 5 votes vote down vote up
/**
 * 获取域的泛型类型,如果不带泛型返回null
 *
 * @param f
 * @return
 */
public static Class<?> getGenericType(Field f) {
    Type type = f.getGenericType();
    if (type instanceof ParameterizedType) {
        type = ((ParameterizedType) type).getActualTypeArguments()[0];
        if (type instanceof Class<?>) return (Class<?>) type;
    } else if (type instanceof Class<?>) return (Class<?>) type;
    return null;
}