com.googlecode.gentyref.GenericTypeReflector Java Examples

The following examples show how to use com.googlecode.gentyref.GenericTypeReflector. 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: ContextKey.java    From elepy with Apache License 2.0 6 votes vote down vote up
static ContextKey<?> forAnnotatedElement(AnnotatedElement element) {
    final Class<?> returnType = ReflectionUtils.returnTypeOf(element);

    if (Crud.class.equals(returnType)) {
        return getTypeArgument(toParameterizedType(element));
    } else if (Crud.class.isAssignableFrom(returnType)) {
        final var exactSuperType = (ParameterizedType) GenericTypeReflector
                .getExactSuperType(
                        getGenericType(element),
                        Crud.class);

        return getTypeArgument(exactSuperType);
    } else {
        return new ContextKey<>(returnType, null);
    }
}
 
Example #2
Source File: FieldUtils.java    From zstack with Apache License 2.0 6 votes vote down vote up
private static GenericType inferCollection(Type type) {
    CollectionGenericType ret = new CollectionGenericType();
    Type valueType = GenericTypeReflector.getTypeParameter(type, Collection.class.getTypeParameters()[0]);
    ret.isInferred = valueType != null;
    if (valueType == null) {
        return ret;
    }

    ret.valueType = GenericTypeReflector.erase(valueType);
    if (Map.class.isAssignableFrom(ret.valueType)) {
        ret.nestedGenericValue = inferMap(valueType);
    } else if (Collection.class.isAssignableFrom(ret.valueType)) {
        ret.nestedGenericValue = inferCollection(valueType);
    }
    return ret;
}
 
Example #3
Source File: LinkCreator.java    From rest-schemagen with Apache License 2.0 6 votes vote down vote up
private void setQueryParameters(final UriBuilder uriBuilder, Scope scope, Object[] parameters) {
    Type[] realParamTypes = GenericTypeReflector.getExactParameterTypes(scope
            .getInvokedMethod(), scope.getInvokedClass());
    visitAnnotations((parameter, parameterIndex, annotation) -> {
        if (annotation instanceof QueryParam && parameter != null) {
            final String parameterName = ((QueryParam) annotation).value();
            if (parameter instanceof Iterable) {
                uriBuilder.queryParam(parameterName, Iterables.toArray((Iterable) parameter, Object.class));
            } else {
                uriBuilder.queryParam(parameterName, parameter.toString());
            }
        } else if (annotation instanceof BeanParam && parameter != null) {
            if (realParamTypes[parameterIndex] instanceof Class<?>) {
                BeanParamExtractor beanParamExtractor = new BeanParamExtractor();
                Map<String, Object[]> queryParameter = beanParamExtractor.getQueryParameters(
                        parameter);
                queryParameter.forEach((uriBuilder::queryParam));
            }
        }
    }, scope.getInvokedMethod(), parameters);
}
 
Example #4
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 #5
Source File: ReflectionUtils.java    From elepy with Apache License 2.0 5 votes vote down vote up
public static Class<?> returnTypeOf(AnnotatedElement field) {
    if (field instanceof AnnotatedType) {
        return (Class) ((AnnotatedType) field).getType();
    }
    if (field instanceof Parameter) {
        return GenericTypeReflector.erase(((Parameter) field).getType());
    }
    return (field instanceof Field) ? ((Field) field).getType() : ((Method) field).getReturnType();
}
 
Example #6
Source File: AbstractNodeTest.java    From flow with Apache License 2.0 5 votes vote down vote up
protected void assertMethodsReturnType(Class<? extends Node<?>> clazz,
        Set<String> ignore) {
    for (Method method : clazz.getMethods()) {
        if (method.getDeclaringClass().equals(Object.class)) {
            continue;
        }
        if (!Modifier.isPublic(method.getModifiers())) {
            continue;
        }
        if (Modifier.isStatic(method.getModifiers())) {
            continue;
        }
        if (method.isBridge()) {
            continue;
        }
        if (method.getName().startsWith("get")
                || method.getName().startsWith("has")
                || method.getName().startsWith("is")
                || ignore.contains(method.getName())) {
            // Ignore
        } else {
            // Setters and such
            Type returnType = GenericTypeReflector
                    .getExactReturnType(method, clazz);
            Assert.assertEquals(
                    "Method " + method.getName()
                            + " has invalid return type",
                    clazz, returnType);
        }
    }
}
 
Example #7
Source File: ParameterDeserializer.java    From flow with Apache License 2.0 5 votes vote down vote up
/**
 * Get the parameter type class.
 *
 * @param navigationTarget
 *            navigation target to get parameter type class for
 * @return parameter type class
 */
public static Class<?> getClassType(Class<?> navigationTarget) {
    Type type = GenericTypeReflector.getTypeParameter(navigationTarget,
            HasUrlParameter.class.getTypeParameters()[0]);
    if (!(type instanceof Class<?>)) {
        throw new IllegalArgumentException(String.format(
                "Parameter type of the given navigationTarget '%s' could not be resolved.",
                navigationTarget.getName()));
    }
    return GenericTypeReflector.erase(type);
}
 
Example #8
Source File: AbstractSinglePropertyField.java    From flow with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private static <T> Class<T> findElementPropertyTypeFromTypeParameter(
        Class<?> hasValueClass) {
    return (Class<T>) GenericTypeReflector
            .erase(GenericTypeReflector.getTypeParameter(hasValueClass,
                    HasValue.class.getTypeParameters()[1]));
}
 
Example #9
Source File: AbstractTemplate.java    From flow with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the type of the template model to use with with this template.
 *
 * @return the model type, not <code>null</code>
 */
@SuppressWarnings("unchecked")
protected Class<? extends M> getModelType() {
    Type type = GenericTypeReflector.getTypeParameter(
            getClass().getGenericSuperclass(),
            AbstractTemplate.class.getTypeParameters()[0]);
    if (type instanceof Class || type instanceof ParameterizedType) {
        return (Class<M>) GenericTypeReflector.erase(type);
    }
    throw new IllegalStateException(getExceptionMessage(type));
}
 
Example #10
Source File: Composite.java    From flow with Apache License 2.0 5 votes vote down vote up
private static Class<? extends Component> findContentType(
        Class<? extends Composite<?>> compositeClass) {
    Type type = GenericTypeReflector.getTypeParameter(
            compositeClass.getGenericSuperclass(),
            Composite.class.getTypeParameters()[0]);
    if (type instanceof Class || type instanceof ParameterizedType) {
        return GenericTypeReflector.erase(type).asSubclass(Component.class);
    }
    throw new IllegalStateException(getExceptionMessage(type));
}
 
Example #11
Source File: ReflectTools.java    From flow with Apache License 2.0 5 votes vote down vote up
/**
 * Finds the Class type for the generic interface class extended by given
 * class if exists.
 *
 * @param clazz
 *            class that should extend interface
 * @param interfaceType
 *            class type of interface to get generic for
 * @return Class if found else {@code null}
 */
public static Class<?> getGenericInterfaceType(Class<?> clazz,
        Class<?> interfaceType) {
    Type type = GenericTypeReflector.getTypeParameter(clazz,
            interfaceType.getTypeParameters()[0]);

    if (type instanceof Class || type instanceof ParameterizedType) {
        return GenericTypeReflector.erase(type);
    }
    return null;
}
 
Example #12
Source File: AbstractServerHandlers.java    From flow with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private final Class<T> getType() {
    Type type = GenericTypeReflector.getTypeParameter(
            getClass().getGenericSuperclass(),
            getClass().getSuperclass().getTypeParameters()[0]);
    if (type instanceof Class || type instanceof ParameterizedType) {
        return (Class<T>) GenericTypeReflector.erase(type);
    }
    throw new IllegalStateException(getExceptionMessage(type));
}
 
Example #13
Source File: WebComponentExporterAwareValidator.java    From flow with Apache License 2.0 5 votes vote down vote up
@Override
protected Optional<String> handleNonRouterLayout(Class<?> clazz) {
    if (WebComponentExporter.class
            .isAssignableFrom(GenericTypeReflector.erase(clazz))) {
        return Optional.empty();
    }
    return Optional.of(String.format(
            "Class '%s' contains '%s', but it is not a router "
                    + "layout/top level route/web component.",
            clazz.getName(), getClassAnnotations(clazz)));
}
 
Example #14
Source File: RouteRegistryInitializer.java    From flow with Apache License 2.0 5 votes vote down vote up
private boolean handleAmbiguousRoute(RouteConfiguration routeConfiguration,
        Class<? extends Component> configuredNavigationTarget,
        Class<? extends Component> navigationTarget) {
    if (GenericTypeReflector.isSuperType(navigationTarget,
            configuredNavigationTarget)) {
        return true;
    } else if (GenericTypeReflector.isSuperType(configuredNavigationTarget,
            navigationTarget)) {
        routeConfiguration.removeRoute(configuredNavigationTarget);
        routeConfiguration.setAnnotatedRoute(navigationTarget);
        return true;
    }
    return false;
}
 
Example #15
Source File: ClassFinder.java    From flow with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <T> Set<Class<? extends T>> getSubTypesOf(Class<T> type) {
    return this.classes.stream()
            .filter(cl -> GenericTypeReflector.isSuperType(type, cl)
                    && !type.equals(cl))
            .map(cl -> (Class<T>) cl).collect(Collectors.toSet());
}
 
Example #16
Source File: ListModelType.java    From flow with Apache License 2.0 5 votes vote down vote up
@Override
public <C> ComplexModelType<C> cast(Class<C> proxyType) {
    if (getItemType() instanceof ListModelType<?>
            && GenericTypeReflector.erase(proxyType).equals(List.class)) {
        return (ComplexModelType<C>) this;
    }
    throw new IllegalArgumentException(
            "Got " + proxyType + ", expected list type");

}
 
Example #17
Source File: ModelEncoder.java    From flow with Apache License 2.0 5 votes vote down vote up
/**
 * Get the encoded type of this encoder.
 *
 * @return the model type
 */
@SuppressWarnings("unchecked")
default Class<E> getEncodedType() {
    Type type = GenericTypeReflector.getTypeParameter(this.getClass(),
            ModelEncoder.class.getTypeParameters()[1]);
    if (type instanceof Class<?>) {
        return (Class<E>) GenericTypeReflector.erase(type);
    }
    throw new InvalidTemplateModelException(String.format(
            "Could not detect the presentation type of %s '%s'. "
                    + "The method 'getEncodedType' needs to be overridden manually.",
            ModelEncoder.class.getSimpleName(), this.getClass().getName()));
}
 
Example #18
Source File: Binder.java    From flow with Apache License 2.0 5 votes vote down vote up
/**
 * Binds {@code property} with {@code propertyType} to the field in the
 * {@code objectWithMemberFields} instance using {@code memberField} as a
 * reference to a member.
 *
 * @param objectWithMemberFields
 *            the object that contains (Java) member fields to build and
 *            bind
 * @param memberField
 *            reference to a member field to bind
 * @param property
 *            property name to bind
 * @param propertyType
 *            type of the property
 * @return {@code true} if property is successfully bound
 */
private boolean bindProperty(Object objectWithMemberFields,
        Field memberField, String property, Class<?> propertyType) {
    Type valueType = GenericTypeReflector.getTypeParameter(
            memberField.getGenericType(),
            HasValue.class.getTypeParameters()[1]);
    if (valueType == null) {
        throw new IllegalStateException(String.format(
                "Unable to detect value type for the member '%s' in the "
                        + "class '%s'.",
                memberField.getName(),
                objectWithMemberFields.getClass().getName()));
    }
    if (propertyType.equals(GenericTypeReflector.erase(valueType))) {
        HasValue<?, ?> field;
        // Get the field from the object
        try {
            field = (HasValue<?, ?>) ReflectTools.getJavaFieldValue(
                    objectWithMemberFields, memberField, HasValue.class);
        } catch (IllegalArgumentException | IllegalAccessException
                | InvocationTargetException e) {
            // If we cannot determine the value, just skip the field
            return false;
        }
        if (field == null) {
            field = makeFieldInstance(
                    (Class<? extends HasValue<?, ?>>) memberField
                            .getType());
            initializeField(objectWithMemberFields, memberField, field);
        }
        forField(field).bind(property);
        return true;
    } else {
        throw new IllegalStateException(String.format(
                "Property type '%s' doesn't "
                        + "match the field type '%s'. "
                        + "Binding should be configured manually using converter.",
                propertyType.getName(), valueType.getTypeName()));
    }
}
 
Example #19
Source File: ModelEncoder.java    From flow with Apache License 2.0 5 votes vote down vote up
/**
 * Get the decoded type of this encoder.
 *
 * @return the application type
 */
@SuppressWarnings("unchecked")
default Class<D> getDecodedType() {
    Type type = GenericTypeReflector.getTypeParameter(this.getClass(),
            ModelEncoder.class.getTypeParameters()[0]);
    if (type instanceof Class<?>) {
        return (Class<D>) GenericTypeReflector.erase(type);
    }
    throw new InvalidTemplateModelException(String.format(
            "Could not detect the model type of %s '%s'. "
                    + "The method 'getDecodedType' needs to be overridden manually.",
            ModelEncoder.class.getSimpleName(), this.getClass().getName()));
}
 
Example #20
Source File: FieldUtils.java    From zstack with Apache License 2.0 5 votes vote down vote up
public static GenericType inferGenericTypeOnMapOrCollectionField(Field field) {
    Class owner = field.getDeclaringClass();
    Type t = GenericTypeReflector.getExactFieldType(field, owner);
    if (Map.class.isAssignableFrom(field.getType())) {
        return inferMap(t);
    } else if (Collection.class.isAssignableFrom(field.getType())) {
        return inferCollection(t);
    } else {
        throw new IllegalArgumentException(String.format("field is type of %s, only Map or Collection field can be inferred", field.getType().getName()));
    }
}
 
Example #21
Source File: FieldUtils.java    From zstack with Apache License 2.0 5 votes vote down vote up
private static GenericType inferMap(Type type) {
    MapGenericType ret = new MapGenericType();
    Type keyType = GenericTypeReflector.getTypeParameter(type, Map.class.getTypeParameters()[0]);
    Type valueType = GenericTypeReflector.getTypeParameter(type, Map.class.getTypeParameters()[1]);
    ret.isInferred = keyType != null && valueType != null;
    if (keyType == null || valueType == null) {
        return ret;
    }

    ret.keyType = GenericTypeReflector.erase(keyType);
    ret.valueType = GenericTypeReflector.erase(valueType);
    if (!ret.isInferred) {
        return ret;
    }

    if (Map.class.isAssignableFrom(ret.keyType)) {
        ret.nestedGenericKey = inferMap(keyType);
    } else if (Collection.class.isAssignableFrom(ret.keyType)) {
        ret.nestedGenericKey = inferCollection(keyType);
    }

    if (Map.class.isAssignableFrom(ret.valueType)) {
        ret.nestedGenericValue = inferMap(valueType);
    } else if (Collection.class.isAssignableFrom(ret.valueType)) {
        ret.nestedGenericValue = inferCollection(valueType);
    }

    return ret;
}
 
Example #22
Source File: GenericParameterizedTypeTest.java    From rest-schemagen with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetContainedTypeWithGenericTypeParameter() throws NoSuchFieldException {
    final Class<?> superclass = getClass().getSuperclass();
    final Field field = superclass.getDeclaredField("object");
    final Type type = GenericTypeReflector.getExactFieldType(field, getClass());

    final GenericType<?> genericType = GenericType.of(type);

    assertThat(genericType.getRawType()).isEqualTo(Boolean.class);
}
 
Example #23
Source File: GenericParameterizedTypeTest.java    From rest-schemagen with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetContainedType() throws NoSuchFieldException {
    final Field field = getClass().getDeclaredField("doubleList");
    final Type type = GenericTypeReflector.getExactFieldType(field, getClass());

    @SuppressWarnings("rawtypes")
    final GenericParameterizedType<List> genericType = new GenericParameterizedType<>(
            (ParameterizedType) type, List.class);

    final GenericType<?> containedType1 = genericType.getContainedType();
    assertThat(containedType1.getRawType()).isEqualTo(List.class);

    final GenericType<?> containedType2 = containedType1.getContainedType();
    assertThat(containedType2.getRawType()).isEqualTo(Double.class);
}
 
Example #24
Source File: GenericClass.java    From rest-schemagen with Apache License 2.0 5 votes vote down vote up
@Override
public GenericType<?> getContainedType() {
    if (getRawType().isArray()) {
        return GenericType.of(GenericTypeReflector.getArrayComponentType(getRawType()),
                getRawType().getComponentType());
    }
    throw new IllegalAccessError("GenericClass " + getSimpleName() + " has no contained type");
}
 
Example #25
Source File: TypeRegistry.java    From glitr with MIT License 5 votes vote down vote up
public GraphQLOutputType retrieveGraphQLOutputType(Class declaringClass, Method method) {
    GraphQLOutputType graphQLOutputType;
    String name = ReflectionUtil.sanitizeMethodName(method.getName());

    graphQLOutputType = getGraphQLOutputTypeFromAnnotationsOnGetter(declaringClass, method);
    graphQLOutputType = getGraphQLOutputTypeFromAnnotationsOnField(declaringClass, method, graphQLOutputType, name);

    // default OutputType
    if (graphQLOutputType == null) {
        graphQLOutputType = (GraphQLOutputType) convertToGraphQLOutputType(GenericTypeReflector.getExactReturnType(method, declaringClass), name);

        // is this an optional field
        boolean nullable = ReflectionUtil.isAnnotatedElementNullable(method);
        if (nullable) { // check the field too
            try {
                Field field = declaringClass.getDeclaredField(name);
                nullable = ReflectionUtil.isAnnotatedElementNullable(field);
            } catch (NoSuchFieldException e) {
                // do nothing
            }
        }

        if (!nullable || name.equals("id")) {
            graphQLOutputType = new GraphQLNonNull(graphQLOutputType);
        }
    }

    return graphQLOutputType;
}
 
Example #26
Source File: GraphQLInputObjectTypeFactory.java    From glitr with MIT License 5 votes vote down vote up
private GraphQLInputObjectField getGraphQLInputObjectField(Pair<Method, Class> pair) {
    Method method = pair.getLeft();
    Class declaringClass = pair.getRight();

    String name = ReflectionUtil.sanitizeMethodName(method.getName());
    String description = ReflectionUtil.getDescriptionFromAnnotatedElement(method);
    if (description != null && description.equals(GlitrDescription.DEFAULT_DESCRIPTION)) {
        description = ReflectionUtil.getDescriptionFromAnnotatedField(declaringClass, method);
    }

    GraphQLType graphQLType = typeRegistry.convertToGraphQLInputType(GenericTypeReflector.getExactReturnType(method, declaringClass), name);
    if (!(graphQLType instanceof GraphQLInputType)) {
        throw new GlitrException("Failed to create GraphQLInputType [" + graphQLType.getName() + "] in class [" + declaringClass.getName() + "]. " +
                "This is most often the result of a GraphQLOutputType of the same name already existing as input types require unique names. " +
                "Please make sure the name used for this input does not match that of another domain class.");
    }
    GraphQLInputType graphQLInputType = (GraphQLInputType) graphQLType;

    boolean nullable = ReflectionUtil.isAnnotatedElementNullable(method);
    if (nullable) { // check the field too
        try {
            Field field = declaringClass.getDeclaredField(name);
            nullable = ReflectionUtil.isAnnotatedElementNullable(field);
        } catch (NoSuchFieldException e) {
            // do nothing
        }
    }

    if (!nullable || name.equals("id")) {
        graphQLInputType = new GraphQLNonNull(graphQLInputType);
    }

    return newInputObjectField()
            .type(graphQLInputType)
            .name(name)
            .description(description)
            // TODO: add default value feature, via annotation?
            .build();
}
 
Example #27
Source File: GenericArray.java    From rest-schemagen with Apache License 2.0 4 votes vote down vote up
@Override
public GenericType<?> getContainedType() {
    return of(GenericTypeReflector.getArrayComponentType(arrayType), getRawType()
            .getComponentType());
}
 
Example #28
Source File: GenericParameterizedType.java    From rest-schemagen with Apache License 2.0 4 votes vote down vote up
@Override
public GenericType<? super T> getSuperType() {
    final Class<? super T> superclass = getRawType().getSuperclass();
    return superclass != null ? GenericType.of(GenericTypeReflector.getExactSuperType(type,
            superclass), superclass) : null;
}
 
Example #29
Source File: GenericClass.java    From rest-schemagen with Apache License 2.0 4 votes vote down vote up
@Override
public GenericType<? super T> getSuperType() {
    final Class<? super T> superclass = getRawType().getSuperclass();
    return superclass != null ? GenericType.of(GenericTypeReflector.getExactSuperType(
            getRawType(), superclass), superclass) : null;
}
 
Example #30
Source File: Scope.java    From rest-schemagen with Apache License 2.0 4 votes vote down vote up
public Type getReturnType() {
    return GenericTypeReflector.getExactReturnType(invokedMethod, invokedClass);
}