java.lang.reflect.ParameterizedType Java Examples

The following examples show how to use java.lang.reflect.ParameterizedType. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: C$Gson$Types.java    From letv with Apache License 2.0 6 votes vote down vote up
public static Type canonicalize(Type type) {
    if (type instanceof Class) {
        Class<?> c = (Class) type;
        return c.isArray() ? new GenericArrayTypeImpl(C$Gson$Types.canonicalize(c.getComponentType())) : c;
    } else if (type instanceof ParameterizedType) {
        ParameterizedType p = (ParameterizedType) type;
        return new ParameterizedTypeImpl(p.getOwnerType(), p.getRawType(), p.getActualTypeArguments());
    } else if (type instanceof GenericArrayType) {
        return new GenericArrayTypeImpl(((GenericArrayType) type).getGenericComponentType());
    } else {
        if (!(type instanceof WildcardType)) {
            return type;
        }
        WildcardType w = (WildcardType) type;
        return new WildcardTypeImpl(w.getUpperBounds(), w.getLowerBounds());
    }
}
 
Example #2
Source File: PojoToRamlImpl.java    From raml-java-tools with Apache License 2.0 6 votes vote down vote up
@Override
public TypeBuilder name(Type type) {

    if ( type instanceof Class) {
        return name((Class<?>)type);
    } else {
        if ( type instanceof ParameterizedType ) {

            ParameterizedType pt = (ParameterizedType) type;
            if ( pt.getRawType() instanceof Class && Collection.class.isAssignableFrom((Class)pt.getRawType()) &&  pt.getActualTypeArguments().length == 1) {

                Class<?> cls = (Class<?>) pt.getActualTypeArguments()[0];
                TypeBuilder builder = name(cls);
                return TypeBuilder.arrayOf(builder);
            } else {
                throw new IllegalArgumentException("can't parse type " + pt);
            }
        } else {

            throw new IllegalArgumentException("can't parse type " + type);
        }
    }
}
 
Example #3
Source File: ClassUtils.java    From dubbox-hystrix with Apache License 2.0 6 votes vote down vote up
public static Class<?> getGenericClass(Class<?> cls, int i) {
    try {
        ParameterizedType parameterizedType = ((ParameterizedType) cls.getGenericInterfaces()[0]);
        Object genericClass = parameterizedType.getActualTypeArguments()[i];
        if (genericClass instanceof ParameterizedType) { // 处理多级泛型
            return (Class<?>) ((ParameterizedType) genericClass).getRawType();
        } else if (genericClass instanceof GenericArrayType) { // 处理数组泛型
            return (Class<?>) ((GenericArrayType) genericClass).getGenericComponentType();
        } else if (genericClass != null) {
            return (Class<?>) genericClass;
        }
    } catch (Throwable e) {
    }
    if (cls.getSuperclass() != null) {
        return getGenericClass(cls.getSuperclass(), i);
    } else {
        throw new IllegalArgumentException(cls.getName() + " generic type undefined!");
    }
}
 
Example #4
Source File: TypeUtil.java    From feilong-core with Apache License 2.0 6 votes vote down vote up
/**
 * 提取实际的泛型参数数组.
 *
 * @param parameterizedType
 *            the parameterized type
 * @return 如果 <code>parameterizedType</code> 是null,抛出 {@link NullPointerException}<br>
 *         如果 <code>parameterizedType</code> 没有实际的泛型参数 {@link ParameterizedType#getActualTypeArguments()},抛出
 *         {@link NullPointerException}<br>
 * @see java.lang.reflect.ParameterizedType#getActualTypeArguments()
 * @since 1.1.1
 */
private static Class<?>[] extractActualTypeArgumentClassArray(ParameterizedType parameterizedType){
    Validate.notNull(parameterizedType, "parameterizedType can't be null/empty!");
    if (LOGGER.isTraceEnabled()){
        LOGGER.trace("parameterizedType info:[{}]", parameterizedType);
    }

    //---------------------------------------------------------------
    Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
    Validate.notNull(actualTypeArguments, "actualTypeArguments can't be null/empty!");

    //---------------------------------------------------------------

    if (LOGGER.isTraceEnabled()){
        LOGGER.trace("actualTypeArguments:[{}]", ConvertUtil.toString(actualTypeArguments, ToStringConfig.DEFAULT_CONNECTOR));
    }
    return convert(actualTypeArguments, Class[].class);
}
 
Example #5
Source File: BuiltInParameterTransformer.java    From cucumber with MIT License 6 votes vote down vote up
private Type getOptionalGenericType(Type type) {
    if (Optional.class.equals(type)) {
        return Object.class;
    }

    if (!(type instanceof ParameterizedType)) {
        return null;
    }

    ParameterizedType parameterizedType = (ParameterizedType) type;
    if (Optional.class.equals(parameterizedType.getRawType())) {
        return parameterizedType.getActualTypeArguments()[0];
    }

    return null;
}
 
Example #6
Source File: CustomFieldArgumentsFunc.java    From glitr with MIT License 6 votes vote down vote up
@Override
public List<GraphQLArgument> call(@Nullable Field field, Method method, Class declaringClass, Annotation annotation) {
    // if same annotation is detected on both field and getter we fail. Only one annotation is allowed. We can talk about having precedence logic later.
    if (method.isAnnotationPresent(annotation.annotationType()) && field != null && field.isAnnotationPresent(annotation.annotationType())) {
        throw new IllegalArgumentException("Conflict: GraphQL Annotations can't be added to both field and getter. Pick one for "+
                                                   annotation.annotationType() + " on " + field.getName() + " and " + method.getName());
    }

    Type returnType = GenericTypeReflector.getExactReturnType(method, declaringClass);
    if (returnType instanceof ParameterizedType) {
        ParameterizedType parameterizedType = (ParameterizedType) returnType;

        Type containerType = parameterizedType.getRawType();
        if (Collection.class.isAssignableFrom((Class) containerType)) {
            List<GraphQLArgument> arguments = new ArrayList<>();
            arguments.add(newArgument().name(GlitrForwardPagingArguments.FIRST).type(GraphQLInt).build());
            arguments.add(newArgument().name(GlitrForwardPagingArguments.AFTER).type(GraphQLString).build());
            return arguments;
        }
    }

    return new ArrayList<>();
}
 
Example #7
Source File: TypeResolver.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Resolves all type variables in {@code type} and all downstream types and returns a
 * corresponding type with type variables resolved.
 */


public Type resolveType(Type type) {
  checkNotNull(type);
  if (type instanceof TypeVariable) {
    return typeTable.resolve((TypeVariable<?>) type);
  } else if (type instanceof ParameterizedType) {
    return resolveParameterizedType((ParameterizedType) type);
  } else if (type instanceof GenericArrayType) {
    return resolveGenericArrayType((GenericArrayType) type);
  } else if (type instanceof WildcardType) {
    return resolveWildcardType((WildcardType) type);
  } else {
    // if Class<?>, no resolution needed, we are done.
    return type;
  }
}
 
Example #8
Source File: FieldType.java    From jspoon with MIT License 6 votes vote down vote up
private Class<?> resolveClass(Type type, Class<?> subType) {
    if (type instanceof Class) {
        return (Class<?>) type;
    } else if (type instanceof ParameterizedType) {
        return resolveClass(((ParameterizedType) type).getRawType(), subType);
    } else if (type instanceof GenericArrayType) {
        GenericArrayType gat = (GenericArrayType) type;
        Class<?> component = resolveClass(gat.getGenericComponentType(), subType);
        return Array.newInstance(component, 0).getClass();
    } else if (type instanceof TypeVariable<?>) {
        TypeVariable<?> variable = (TypeVariable<?>) type;
        Type resolvedType = getTypeVariableMap(subType).get(variable);
        return (resolvedType == null) ? resolveClass(resolveBound(variable), subType)
                : resolveClass(resolvedType, subType);
    } else if (type instanceof WildcardType) {
        WildcardType wcType = (WildcardType) type;
        Type[] bounds = wcType.getLowerBounds().length == 0 ? wcType.getUpperBounds()
                : wcType.getLowerBounds();
        return resolveClass(bounds[0], subType);
    }
    // there are no more types in a standard JDK
    throw new IllegalArgumentException("Unknown type: " + type);
}
 
Example #9
Source File: SlimAdapter.java    From SlimAdapter with MIT License 6 votes vote down vote up
private boolean isTypeMatch(Type type, Type targetType) {
    if (type instanceof Class && targetType instanceof Class) {
        if (((Class) type).isAssignableFrom((Class) targetType)) {
            return true;
        }
    } else if (type instanceof ParameterizedType && targetType instanceof ParameterizedType) {
        ParameterizedType parameterizedType = (ParameterizedType) type;
        ParameterizedType parameterizedTargetType = (ParameterizedType) targetType;
        if (isTypeMatch(parameterizedType.getRawType(), ((ParameterizedType) targetType).getRawType())) {
            Type[] types = parameterizedType.getActualTypeArguments();
            Type[] targetTypes = parameterizedTargetType.getActualTypeArguments();
            if (types == null || targetTypes == null || types.length != targetTypes.length) {
                return false;
            }
            int len = types.length;
            for (int i = 0; i < len; i++) {
                if (!isTypeMatch(types[i], targetTypes[i])) {
                    return false;
                }
            }
            return true;
        }
    }
    return false;
}
 
Example #10
Source File: TypeUtils.java    From BaseProject with Apache License 2.0 6 votes vote down vote up
public static boolean hasUnresolvableType(Type type) {
    if (type instanceof Class<?>) {
        return false;
    }
    if (type instanceof ParameterizedType) {
        ParameterizedType parameterizedType = (ParameterizedType) type;
        for (Type typeArgument : parameterizedType.getActualTypeArguments()) {
            if (hasUnresolvableType(typeArgument)) {
                return true;
            }
        }
        return false;
    }
    if (type instanceof GenericArrayType) {
        return hasUnresolvableType(((GenericArrayType) type).getGenericComponentType());
    }
    if (type instanceof TypeVariable) {
        return true;
    }
    if (type instanceof WildcardType) {
        return true;
    }
    String className = type == null ? "null" : type.getClass().getName();
    throw new IllegalArgumentException("Expected a Class, ParameterizedType, or " + "GenericArrayType, but <" + type + "> is of type " + className);
}
 
Example #11
Source File: DefaultFieldDecorator.java    From selenium with Apache License 2.0 6 votes vote down vote up
protected boolean isDecoratableList(Field field) {
  if (!List.class.isAssignableFrom(field.getType())) {
    return false;
  }

  // Type erasure in Java isn't complete. Attempt to discover the generic
  // type of the list.
  Type genericType = field.getGenericType();
  if (!(genericType instanceof ParameterizedType)) {
    return false;
  }

  Type listType = ((ParameterizedType) genericType).getActualTypeArguments()[0];

  if (!WebElement.class.equals(listType)) {
    return false;
  }

  return field.getAnnotation(FindBy.class) != null ||
         field.getAnnotation(FindBys.class) != null ||
         field.getAnnotation(FindAll.class) != null;
}
 
Example #12
Source File: InjectorImpl.java    From businessworks with Apache License 2.0 6 votes vote down vote up
/**
 * Converts a binding for a {@code Key<TypeLiteral<T>>} to the value {@code TypeLiteral<T>}. It's
 * a bit awkward because we have to pull out the inner type in the type literal.
 */
private <T> BindingImpl<TypeLiteral<T>> createTypeLiteralBinding(
    Key<TypeLiteral<T>> key, Errors errors) throws ErrorsException {
  Type typeLiteralType = key.getTypeLiteral().getType();
  if (!(typeLiteralType instanceof ParameterizedType)) {
    throw errors.cannotInjectRawTypeLiteral().toException();
  }

  ParameterizedType parameterizedType = (ParameterizedType) typeLiteralType;
  Type innerType = parameterizedType.getActualTypeArguments()[0];

  // this is unforunate. We don't support building TypeLiterals for type variable like 'T'. If
  // this proves problematic, we can probably fix TypeLiteral to support type variables
  if (!(innerType instanceof Class)
      && !(innerType instanceof GenericArrayType)
      && !(innerType instanceof ParameterizedType)) {
    throw errors.cannotInjectTypeLiteralOf(innerType).toException();
  }

  @SuppressWarnings("unchecked") // by definition, innerType == T, so this is safe
  TypeLiteral<T> value = (TypeLiteral<T>) TypeLiteral.get(innerType);
  InternalFactory<TypeLiteral<T>> factory = new ConstantFactory<TypeLiteral<T>>(
      Initializables.of(value));
  return new InstanceBindingImpl<TypeLiteral<T>>(this, key, SourceProvider.UNKNOWN_SOURCE,
      factory, ImmutableSet.<InjectionPoint>of(), value);
}
 
Example #13
Source File: Reflections.java    From hermes with Apache License 2.0 6 votes vote down vote up
/**
 * 通过反射, 获得Class定义中声明的父类的泛型参数的类型.
 * 如无法找到, 返回Object.class.
 * 
 * 如public UserDao extends HibernateDao<User,Long>
 * 
 * @param clazz clazz The class to introspect
 * @param index the Index of the generic ddeclaration,start from 0.
 * @return the index generic declaration, or Object.class if cannot be determined
 */
@SuppressWarnings("rawtypes")
public static Class getClassGenricType(final Class clazz, final int index) {

	Type genType = clazz.getGenericSuperclass();

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

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

	if ((index >= params.length) || (index < 0)) {
		logger.warn("Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: "
				+ params.length);
		return Object.class;
	}
	if (!(params[index] instanceof Class)) {
		logger.warn(clazz.getSimpleName() + " not set the actual class on superclass generic parameter");
		return Object.class;
	}

	return (Class) params[index];
}
 
Example #14
Source File: LineMessageHandlerSupport.java    From line-bot-sdk-java with Apache License 2.0 6 votes vote down vote up
private int getPriority(final EventMapping mapping, final Type type) {
    if (mapping.priority() != EventMapping.DEFAULT_PRIORITY_VALUE) {
        return mapping.priority();
    }

    if (type == Event.class) {
        return EventMapping.DEFAULT_PRIORITY_FOR_EVENT_IFACE;
    }

    if (type instanceof Class) {
        return ((Class<?>) type).isInterface()
               ? EventMapping.DEFAULT_PRIORITY_FOR_IFACE
               : EventMapping.DEFAULT_PRIORITY_FOR_CLASS;
    }

    if (type instanceof ParameterizedType) {
        return EventMapping.DEFAULT_PRIORITY_FOR_PARAMETRIZED_TYPE;
    }

    throw new IllegalStateException();
}
 
Example #15
Source File: OptionalMessageBodyWriter.java    From dropwizard-java8 with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({"rawtypes", "unchecked"})
@Override
public void writeTo(Optional<?> entity,
                    Class<?> type,
                    Type genericType,
                    Annotation[] annotations,
                    MediaType mediaType,
                    MultivaluedMap<String, Object> httpHeaders,
                    OutputStream entityStream)
        throws IOException {
    if (!entity.isPresent()) {
        throw new NotFoundException();
    }

    final Type innerGenericType = (genericType instanceof ParameterizedType) ?
        ((ParameterizedType) genericType).getActualTypeArguments()[0] : entity.get().getClass();

    MessageBodyWriter writer = mbw.get().getMessageBodyWriter(entity.get().getClass(),
        innerGenericType, annotations, mediaType);
    writer.writeTo(entity.get(), entity.get().getClass(),
        innerGenericType, annotations, mediaType, httpHeaders, entityStream);
}
 
Example #16
Source File: ReflectionNavigator.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
public Type onParameterizdType(ParameterizedType p, BinderArg args) {
    Type[] params = p.getActualTypeArguments();

    boolean different = false;
    for (int i = 0; i < params.length; i++) {
        Type t = params[i];
        params[i] = visit(t, args);
        different |= t != params[i];
    }

    Type newOwner = p.getOwnerType();
    if (newOwner != null) {
        newOwner = visit(newOwner, args);
    }
    different |= p.getOwnerType() != newOwner;

    if (!different) {
        return p;
    }

    return new ParameterizedTypeImpl((Class<?>) p.getRawType(), params, newOwner);
}
 
Example #17
Source File: BaseHelper.java    From AndroidStudyDemo with GNU General Public License v2.0 6 votes vote down vote up
private void generateControl(Class clazz) {
    Type type = clazz.getGenericSuperclass(); //获得带有泛型的父类
    if (type instanceof ParameterizedType) {
        ParameterizedType p = (ParameterizedType) type; //获得参数化类型,即泛型
        Type[] arrayClasses = p.getActualTypeArguments(); //获取参数化类型的数组,泛型可能有多个

        for (Type item : arrayClasses) {
            if (item instanceof Class) {
                Class<T> tClass = (Class<T>) item;

                if (tClass.equals(BaseControl.class) || (tClass.getSuperclass() != null &&
                        tClass.getSuperclass().equals(BaseControl.class))) {
                    messageProxy = new MessageProxy(mHandler);
                    mControl = ControlFactory.getControlInstance(tClass, messageProxy);
                    mModel = new ModelMap();
                    mControl.setModel(mModel);
                    return;
                }
            }
        }
    }
}
 
Example #18
Source File: ReflectionNavigator.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public Type onParameterizdType(ParameterizedType p, BinderArg args) {
    Type[] params = p.getActualTypeArguments();

    boolean different = false;
    for (int i = 0; i < params.length; i++) {
        Type t = params[i];
        params[i] = visit(t, args);
        different |= t != params[i];
    }

    Type newOwner = p.getOwnerType();
    if (newOwner != null) {
        newOwner = visit(newOwner, args);
    }
    different |= p.getOwnerType() != newOwner;

    if (!different) {
        return p;
    }

    return new ParameterizedTypeImpl((Class<?>) p.getRawType(), params, newOwner);
}
 
Example #19
Source File: InjectionUtils.java    From cxf with Apache License 2.0 6 votes vote down vote up
public static Type processGenericTypeIfNeeded(Class<?> serviceCls, Class<?> paramCls, Type type) {

        if (type instanceof TypeVariable) {
            type = InjectionUtils.getSuperType(serviceCls, (TypeVariable<?>)type);
        } else if (type instanceof ParameterizedType) {
            ParameterizedType pt = (ParameterizedType)type;
            if (pt.getActualTypeArguments()[0] instanceof TypeVariable
                && isSupportedCollectionOrArray(getRawType(pt))) {
                TypeVariable<?> typeVar = (TypeVariable<?>)pt.getActualTypeArguments()[0];
                Type theType = InjectionUtils.getSuperType(serviceCls, typeVar);
                if (theType instanceof Class) {
                    type = new ParameterizedCollectionType((Class<?>)theType);
                } else {
                    type = processGenericTypeIfNeeded(serviceCls, paramCls, theType);
                    type = new ParameterizedCollectionType(type);
                }
            }
        }

        if (type == null || type == Object.class) {
            type = paramCls;
        }
        return type;

    }
 
Example #20
Source File: Generics.java    From atomix with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the generic type at the given position for the given interface.
 *
 * @param instance the implementing instance
 * @param iface    the generic interface
 * @param position the generic position
 * @return the generic type at the given position
 */
public static Type getGenericInterfaceType(Object instance, Class<?> iface, int position) {
  Class<?> type = instance.getClass();
  while (type != Object.class) {
    for (Type genericType : type.getGenericInterfaces()) {
      if (genericType instanceof ParameterizedType) {
        ParameterizedType parameterizedType = (ParameterizedType) genericType;
        if (parameterizedType.getRawType() == iface) {
          return parameterizedType.getActualTypeArguments()[position];
        }
      }
    }
    type = type.getSuperclass();
  }
  return null;
}
 
Example #21
Source File: JSONPropertyTest.java    From squidb with Apache License 2.0 6 votes vote down vote up
private <T> T deserializeObject(Object object, Type type) throws JSONException {
    if (JSONObject.NULL == object) {
        return null;
    }
    if (!(object instanceof JSONObject)) {
        return (T) object;
    }
    JSONObject jsonObject = (JSONObject) object;
    if (JSONPojo.class.equals(type)) {
        JSONPojo result = new JSONPojo();
        result.pojoInt = jsonObject.getInt("pojoInt");
        result.pojoDouble = jsonObject.getDouble("pojoDouble");
        result.pojoStr = jsonObject.getString("pojoStr");
        result.pojoList = deserializeArray(jsonObject.getJSONArray("pojoList"), Integer.class);
        return (T) result;
    } else if (type instanceof ParameterizedType && Map.class
            .equals(((ParameterizedType) type).getRawType())) {
        return (T) deserializeMap(jsonObject, ((ParameterizedType) type).getActualTypeArguments()[1]);
    }
    throw new JSONException("Unable to parse object " + object);
}
 
Example #22
Source File: JSONOptions.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public <T> T getListWith(ObjectMapper mapper, TypeReference<T> t) throws IOException {
  if (opaque != null) {
    Type c = t.getType();
    if (c instanceof ParameterizedType) {
      c = ((ParameterizedType)c).getRawType();
    }
    if ( c.equals(opaque.getClass())) {
      return (T) opaque;
    } else {
      throw new IOException(String.format("Attempted to retrieve a list with type of %s.  However, the JSON " +
        "options carried an opaque value of type %s.", t.getType(), opaque.getClass().getName()));
    }
  }
  if (root == null) {
    return null;
  }
  return mapper.treeAsTokens(root).readValueAs(t);
}
 
Example #23
Source File: PojoSink.java    From enhydrator with Apache License 2.0 6 votes vote down vote up
protected static Pair<String, Class<? extends Object>> getChildInfo(Class target) {
    Field[] declaredFields = target.getDeclaredFields();
    for (Field field : declaredFields) {
        final Class<?> type = field.getType();
        if (type.isAssignableFrom(Collection.class)) {
            final ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType();
            String clazz = null;
            try {
                clazz = parameterizedType.getActualTypeArguments()[0].getTypeName();
                return new Pair(field.getName(), Class.forName(clazz));
            } catch (ClassNotFoundException ex) {
                throw new IllegalStateException("Cannot find class " + clazz, ex);
            }
        }
    }
    return null;
}
 
Example #24
Source File: WebClientConverterFactory.java    From spring-cloud-square with Apache License 2.0 6 votes vote down vote up
@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
    Class<?> rawType = getRawType(type);
    boolean isMono = rawType == Mono.class;
    if (rawType != Flux.class && !isMono) {

        if (rawType == Response.class) {
            Type publisherType = getParameterUpperBound(0, (ParameterizedType) type);
            Class<?> rawPublisherType = getRawType(publisherType);
            isMono = rawPublisherType == Mono.class;
            boolean isFlux = rawPublisherType == Flux.class;

            if (isMono || isFlux) {
                return EMPTY_CONVERTER;
            }
        }

        return null;
    }
    return EMPTY_CONVERTER;
}
 
Example #25
Source File: ProviderBinder.java    From everrest with Eclipse Public License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public void addExceptionMapper(ObjectFactory<ProviderDescriptor> exceptionMapperFactory) {
    for (Type type : exceptionMapperFactory.getObjectModel().getObjectClass().getGenericInterfaces()) {
        if (type instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType)type;
            if (ExceptionMapper.class == parameterizedType.getRawType()) {
                Type[] typeArguments = parameterizedType.getActualTypeArguments();
                if (typeArguments.length != 1) {
                    throw new RuntimeException("Unable strong determine actual type argument");
                }
                Class<? extends Throwable> errorType = (Class<? extends Throwable>)typeArguments[0];
                if (exceptionMappers.putIfAbsent(errorType, exceptionMapperFactory) != null) {
                    throw new DuplicateProviderException(String.format("ExceptionMapper for exception %s already registered", errorType));
                }
            }
        }
    }
}
 
Example #26
Source File: Methods.java    From raistlic-lib-commons-core with Apache License 2.0 5 votes vote down vote up
private ParameterizedType getPossibleGenericType(Class<?> type) {

      if (ptMap == null) {
        ptMap = new HashMap<>();
        Class<?> declaringClass = overridingMethod.getDeclaringClass();
//        gatherSuperTypes(declaringClass, ptMap);
      }
      return ptMap.get(type);
    }
 
Example #27
Source File: AbstractBeanValidationPropertyPostProcessor.java    From RestDoc with Apache License 2.0 5 votes vote down vote up
private boolean cascadeValid(PropertyModel propertyModel, TypeContext typeContext) {
    PropertyItem parent = propertyModel.getParentPropertyItem();
    if (parent == null) return true;

    Valid validAnno = parent.getAnnotation(Valid.class);
    if (validAnno != null)
        return true;

    AnnotatedType annotatedType = null;
    if (parent.getField() != null) {
        annotatedType = parent.getField().getAnnotatedType();
    } else if (parent.getGetMethod() != null) {
        annotatedType = parent.getGetMethod().getAnnotatedReturnType();
    } else if (parent.getSetMethod() != null) {
        annotatedType = parent.getGetMethod().getAnnotatedParameterTypes()[0];
    }
    if (annotatedType != null) {
        if (annotatedType instanceof AnnotatedParameterizedType) {
            AnnotatedParameterizedType annotatedParameterizedType = (AnnotatedParameterizedType) annotatedType;
            if (annotatedParameterizedType.getType() instanceof ParameterizedType) {
                Class clazz = (Class) ((ParameterizedType) annotatedParameterizedType.getType()).getRawType();
                if (List.class.isAssignableFrom(clazz)) {
                    if (annotatedParameterizedType.getAnnotatedActualTypeArguments()[0].getAnnotation(Valid.class) != null)
                        return true;
                }
            }
        }
    }
    return false;
}
 
Example #28
Source File: DefaultCodecs.java    From r2dbc-mysql with Apache License 2.0 5 votes vote down vote up
@Nullable
private <T> T decodeMassive(LargeFieldValue value, FieldInformation info, ParameterizedType type, boolean binary, CodecContext context) {
    for (MassiveParametrizedCodec<?> codec : massiveParametrizedCodecs) {
        if (codec.canDecode(info, type)) {
            @SuppressWarnings("unchecked")
            T result = (T) codec.decodeMassive(value.getBufferSlices(), info, type, binary, context);
            return result;
        }
    }

    throw new IllegalArgumentException("Cannot decode massive value of type " + type + " for " + info.getType() + " with collation " + info.getCollationId());
}
 
Example #29
Source File: Utils.java    From cxf with Apache License 2.0 5 votes vote down vote up
static Type getTypeFromXmlAdapter(XmlJavaTypeAdapter xjta) {
    if (xjta != null) {
        Class<?> c2 = xjta.value();
        Type sp = c2.getGenericSuperclass();
        while (!XmlAdapter.class.equals(c2) && c2 != null) {
            sp = c2.getGenericSuperclass();
            c2 = c2.getSuperclass();
        }
        if (sp instanceof ParameterizedType) {
            return ((ParameterizedType)sp).getActualTypeArguments()[0];
        }
    }
    return null;
}
 
Example #30
Source File: ModuleManager.java    From android-arch-mvvm with Apache License 2.0 5 votes vote down vote up
private static void checkReturnType(Method method1, Method method2) {
    Class<?> returnType;
    Type returnType1, returnType2;
    if (ModuleCall.class.equals(method1.getReturnType())) { // 异步回调的方法
        returnType = method2.getReturnType();
        if (returnType.equals(Observable.class) || returnType.equals(Single.class) || returnType.equals(Flowable.class) || returnType.equals(Maybe.class)) {

            returnType1 = method1.getGenericReturnType();
            returnType2 = method2.getGenericReturnType();

            if (returnType1 instanceof ParameterizedType && returnType2 instanceof ParameterizedType) { // 都带泛型
                // 检查泛型的类型是否一样
                if (!((ParameterizedType) returnType1).getActualTypeArguments()[0].equals(((ParameterizedType) returnType2).getActualTypeArguments()[0])) {
                    throw new IllegalArgumentException(method1.getName() + "方法的返回值类型的泛型的须一样");
                }
            } else if (!(returnType1 instanceof Class && returnType2 instanceof Class)) {
                throw new IllegalArgumentException(method1.getName() + "方法的返回值类型的泛型的须一样");
            }
        } else {
            throw new IllegalArgumentException(String.format("%s::%s的返回值类型必须是Observable,Single,Flowable,Maybe之一", method2.getDeclaringClass().getSimpleName(), method2.getName()));
        }
    } else {
        if (!method1.getGenericReturnType().equals(method2.getGenericReturnType())) { //同步调用的返回值必须一样
            throw new IllegalArgumentException(method1.getName() + "方法的返回值类型不一样");
        }
    }
}