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   View source code 7 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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;
}