Example usage for java.lang.reflect ParameterizedType getActualTypeArguments

List of usage examples for java.lang.reflect ParameterizedType getActualTypeArguments

Introduction

In this page you can find the example usage for java.lang.reflect ParameterizedType getActualTypeArguments.

Prototype

Type[] getActualTypeArguments();

Source Link

Document

Returns an array of Type objects representing the actual type arguments to this type.

Usage

From source file:com.nginious.http.serialize.JsonDeserializer.java

/**
 * Constructs a new JSON deserializer/*from   w w  w  . j a  v  a2 s  .c o  m*/
 */
public JsonDeserializer() {
    super();
    ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass();
    @SuppressWarnings("unchecked")
    Class<E> clazz = (Class<E>) type.getActualTypeArguments()[0];
    this.name = clazz.getSimpleName();
    this.name = name.substring(0, 1).toLowerCase() + name.substring(1);
}

From source file:com.github.reinert.jjschema.JsonSchemaGenerator.java

private void processPropertyCollection(Method method, Field field, ObjectNode schema) throws TypeException {
    schema.put(TAG_TYPE, TAG_ARRAY);/*from w  ww  .j a v a  2 s. c  o m*/
    Class<?> genericClass = null;
    if (method != null) {
        Type methodType = method.getGenericReturnType();
        if (!ParameterizedType.class.isAssignableFrom(methodType.getClass())) {
            throw new TypeException("Collection property must be parameterized: " + method.getName());
        }
        ParameterizedType genericType = (ParameterizedType) methodType;
        genericClass = (Class<?>) genericType.getActualTypeArguments()[0];
    } else {
        genericClass = field.getClass();
    }
    schema.put("items", generateSchema(genericClass));
}

From source file:com.igormaznitsa.upom.UPomModel.java

private Object processPathStepToGet(final String[] path, final int pathStart, final Object instance)
        throws Exception {
    final String fieldName = path[pathStart];

    if (pathStart == path.length - 1) {
        // last step
        // find getter
        final Method getter = findMethod(instance.getClass(), "get" + fieldName, true);
        if (getter == null) {
            throw new UPomException("Can't find model field '" + makePathStr(path, pathStart) + '\'');
        }//ww  w.jav  a 2 s .  co  m

        final Class[] params = getter.getParameterTypes();
        if (params.length == 0) {
            return ensureCloning(getter.invoke(instance));
        } else {
            final Field field = findDeclaredFieldForName(instance.getClass(), fieldName);
            if (field != null) {
                return getField(instance, field);
            } else {
                throw new UPomException("Unsupported type for '" + makePathStr(path, pathStart) + "\'");
            }
        }
    } else {
        // find getter
        final Method getter = findMethod(instance.getClass(), "get" + fieldName, true);
        if (getter == null) {
            throw new UPomException("Can't find model field '" + makePathStr(path, pathStart) + '\'');
        }
        final Object nextInstance = getter.invoke(instance);
        if (nextInstance == null) {
            return false;
        }

        final boolean theNextPathItemIsLastOne = path.length - 1 == pathStart + 1;

        if (nextInstance instanceof Collection) {
            final Type returnType = getter.getGenericReturnType();
            if (returnType instanceof ParameterizedType) {
                final ParameterizedType paramType = (ParameterizedType) returnType;
                final Type[] argTypes = paramType.getActualTypeArguments();

                if (theNextPathItemIsLastOne) {
                    // take only the first value
                    return ((Collection) nextInstance).isEmpty() ? null
                            : ((Collection) nextInstance).iterator().next();
                }

                final String nextPathItem = path[pathStart + 1].toLowerCase(Locale.ENGLISH);
                if (argTypes[0].toString().toLowerCase(Locale.ENGLISH).endsWith(nextPathItem)) {
                    return ((Collection) nextInstance).isEmpty() ? null
                            : processPathStepToGet(path, pathStart + 2,
                                    ((Collection) nextInstance).iterator().next());
                } else {
                    throw new UPomException(
                            "Collection element type is not '" + makePathStr(path, pathStart + 1) + '\'');
                }
            } else {
                throw new UPomException("Can't find model field '" + makePathStr(path, pathStart) + '\'');
            }
        } else if (nextInstance instanceof Map) {
            final Map map = (Map) nextInstance;
            final String nextPathItem = path[pathStart + 1];
            if (theNextPathItemIsLastOne) {
                return map.get(nextPathItem);
            } else {
                return map.containsKey(nextPathItem)
                        ? processPathStepToGet(path, pathStart + 2, map.get(nextPathItem))
                        : null;
            }
        } else {
            return processPathStepToGet(path, pathStart + 1, nextInstance);
        }
    }
}

From source file:com.github.reinert.jjschema.JsonSchemaGenerator.java

private <T> void processCustomCollection(Class<T> type, ObjectNode schema) throws TypeException {
    schema.put(TAG_TYPE, TAG_ARRAY);/*from  w  ww  .  j  a  v a  2s  .  c  o m*/
    Field field = type.getDeclaredFields()[0];
    ParameterizedType genericType = (ParameterizedType) field.getGenericType();
    Class<?> genericClass = (Class<?>) genericType.getActualTypeArguments()[0];
    ObjectNode itemsSchema = generateSchema(genericClass);
    itemsSchema.remove("$schema");
    schema.put("items", itemsSchema);
}

From source file:org.openmrs.module.metadatasharing.handler.HandlerEngine.java

/**
 * Finds a supported type of the given handler
 * /*from w w w  . j  a v  a 2 s. co  m*/
 * @param handlerType
 * @param handler
 * @return the type
 */
Class<?> findSupportedType(Class<?> handlerType, MetadataHandler<?> handler) {
    Class<?> supportedType = null;

    List<Type> types = new ArrayList<Type>();
    types.addAll(Arrays.asList(handler.getClass().getGenericInterfaces()));
    if (handler.getClass().getGenericSuperclass() != null) {
        types.add(handler.getClass().getGenericSuperclass());
    }

    for (Type type : types) {
        if (type instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) type;
            if (handlerType.isAssignableFrom((Class<?>) parameterizedType.getRawType())) {
                if (parameterizedType.getActualTypeArguments()[0] instanceof Class) {
                    supportedType = (Class<?>) parameterizedType.getActualTypeArguments()[0];
                    break;
                }
            }
        }
    }

    if (supportedType == null) {
        throw new IllegalArgumentException(handler.getClass()
                + " must implement handler interface directly or inherit from a single generic superclass");
    }

    return supportedType;
}

From source file:nz.co.senanque.validationengine.metadata.AnnotationsMetadataFactory.java

private void scanPackageForValidators(String basePackage,
        Map<Class<? extends Annotation>, Class<? extends FieldValidator<Annotation>>> validators)
        throws ClassNotFoundException {

    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(
            true) {//  w w w  .j  av  a  2s.c o m
        private String iface = FieldValidator.class.getCanonicalName();

        /**
         * Check if the class has the right annotation
         * @param metadataReader the ASM ClassReader for the class
         * @return whether the class qualifies as a candidate component
         */
        protected boolean isCandidateComponent(MetadataReader metadataReader) throws IOException {
            AnnotationMetadata metadata = metadataReader.getAnnotationMetadata();
            for (String n : metadata.getInterfaceNames()) {
                if (iface.equals(n)) {
                    return true;
                }
            }
            return false;
        }

        /**
         * Determine whether the given bean definition qualifies as candidate.
         * <p>The default implementation checks whether the class is concrete
         * (i.e. not abstract and not an interface). Can be overridden in subclasses.
         * @param beanDefinition the bean definition to check
         * @return whether the bean definition qualifies as a candidate component
         */
        protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
            return (beanDefinition.getMetadata().isConcrete() && beanDefinition.getMetadata().isIndependent());
        }

    };

    //      String basePackage = "nz/co/senanque/validationengine/fieldvalidators";//nz.co.senanque.validationengine.fieldvalidators
    Set<BeanDefinition> components = provider.findCandidateComponents(basePackage.replace('.', '/'));
    for (BeanDefinition component : components) {
        @SuppressWarnings("unchecked")
        Class<? extends FieldValidator<Annotation>> class_ = (Class<? extends FieldValidator<Annotation>>) Class
                .forName(component.getBeanClassName());
        Type[] types = class_.getGenericInterfaces();
        ParameterizedType t0 = (ParameterizedType) types[0];
        @SuppressWarnings("unchecked")
        Class<? extends Annotation> p = (Class<? extends Annotation>) t0.getActualTypeArguments()[0];
        validators.put(p, class_);
    }
}

From source file:com.igormaznitsa.upom.UPomModel.java

private boolean processPathStepToSet(final String[] path, final int pathStart, final Object instance,
        final Object value) throws Exception {
    final String fieldName = path[pathStart];

    if (pathStart == path.length - 1) {
        // last step
        // find setter
        final Method setter = findMethod(instance.getClass(), "set" + fieldName, true);
        if (setter == null) {
            throw new UPomException("Can't find model field '" + makePathStr(path, pathStart) + '\'');
        }/*  w  ww  .  j a v  a  2s  . c  o  m*/

        final Class[] params = setter.getParameterTypes();
        if (params.length == 0) {
            throw new UPomException("Detected zero setter '" + makePathStr(path, pathStart) + "\'");
        } else if (params.length == 1) {
            setter.invoke(instance, ensureCloning(value));
        } else {
            final Field field = findDeclaredFieldForName(instance.getClass(), fieldName);
            if (field != null) {
                setField(instance, field, value);
            } else {
                throw new UPomException("Unsupported type for '" + makePathStr(path, pathStart) + "\'");
            }
        }
        return true;
    } else {
        // find getter
        final Method getter = findMethod(instance.getClass(), "get" + fieldName, true);
        if (getter == null) {
            throw new UPomException("Can't find model field '" + makePathStr(path, pathStart) + '\'');
        }
        final Object nextInstance = getter.invoke(instance);
        if (nextInstance == null) {
            return false;
        }

        final boolean theNextPathItemIsLastOne = path.length - 1 == pathStart + 1;
        if (nextInstance instanceof Collection) {
            final Type returnType = getter.getGenericReturnType();
            if (returnType instanceof ParameterizedType) {
                final ParameterizedType paramType = (ParameterizedType) returnType;
                final Type[] argTypes = paramType.getActualTypeArguments();

                if (theNextPathItemIsLastOne) {
                    if (value == null) {
                        ((Collection) nextInstance).clear();
                        return true;
                    } else if (value instanceof Collection) {
                        ((Collection) nextInstance).clear();
                        for (final Object obj : ((Collection) value)) {
                            ((Collection) nextInstance).add(obj);
                        }
                        return true;
                    } else {
                        ((Collection) nextInstance).clear();
                        return ((Collection) nextInstance).add(value);
                    }
                }

                final String nextPathItem = path[pathStart + 1].toLowerCase(Locale.ENGLISH);
                if (argTypes[0].toString().toLowerCase(Locale.ENGLISH).endsWith(nextPathItem)) {
                    boolean result = false;
                    for (final Object collectionItem : (Collection) nextInstance) {
                        result |= processPathStepToSet(path, pathStart + 2, collectionItem, value);
                    }
                    return result;
                } else {
                    throw new UPomException(
                            "Collection element type is not '" + makePathStr(path, pathStart + 1) + '\'');
                }
            } else {
                throw new UPomException("Can't find model field '" + makePathStr(path, pathStart) + '\'');
            }
        } else if (nextInstance instanceof Map) {
            final Map map = (Map) nextInstance;
            final String nextPathItem = path[pathStart + 1];
            if (theNextPathItemIsLastOne) {
                if (value == null) {
                    map.remove(nextPathItem);
                } else {
                    map.put(nextPathItem, value);
                }
                return true;
            } else {
                return map.containsKey(nextPathItem)
                        ? processPathStepToSet(path, pathStart + 2, map.get(nextPathItem), value)
                        : false;
            }
        } else {
            return processPathStepToSet(path, pathStart + 1, nextInstance, value);
        }
    }
}

From source file:org.lambdamatic.mongodb.apt.testutil.FieldAssertion.java

/**
 * Checks that the actual field is parameterized.
 * // w  w  w.ja v  a  2 s .  c  o m
 * @param expectedRawType the expected raw type
 * @param expectedTypeArguments the expected type arguments
 * @return this {@link FieldAssertion} for fluent linking
 */
public FieldAssertion isParameterizedType(final Class<?> expectedRawType, final Type... expectedTypeArguments) {
    isNotNull();
    if (!(actual.getGenericType() instanceof ParameterizedType)) {
        failWithMessage("Expected field <%s> to be a parameterized type but it was not", actual);
    }
    final ParameterizedType actualType = (ParameterizedType) actual.getGenericType();
    final ParameterizedType expectedParameterizedType = TypeUtils.parameterize(expectedRawType,
            expectedTypeArguments);
    if (!TypeUtils.equals(actualType, expectedParameterizedType)) {
        failWithMessage("Expected field %s.%s to be of type %s<%s> but it was %s<%s>",
                actual.getType().getName(), actual.getName(), expectedRawType, expectedTypeArguments,
                actualType.getRawType().getTypeName(), actualType.getActualTypeArguments());
    }
    return this;
}

From source file:dstrelec.nats.listener.adapter.MessagingMessageListenerAdapter.java

/**
 * Subclasses can override this method to use a different mechanism to determine
 * the target type of the payload conversion.
 * @param method the method.//from w w  w .  java 2s.c  o  m
 * @return the type.
 */
protected Type determineInferredType(Method method) {
    if (method == null) {
        return null;
    }

    Type genericParameterType = null;

    for (int i = 0; i < method.getParameterTypes().length; i++) {
        MethodParameter methodParameter = new MethodParameter(method, i);
        /*
         * We're looking for a single non-annotated parameter, or one annotated with @Payload.
         * We ignore parameters with type Message because they are not involved with conversion.
         */
        if (eligibleParameter(methodParameter) && (methodParameter.getParameterAnnotations().length == 0
                || methodParameter.hasParameterAnnotation(Payload.class))) {
            if (genericParameterType == null) {
                genericParameterType = methodParameter.getGenericParameterType();
                if (genericParameterType instanceof ParameterizedType) {
                    ParameterizedType parameterizedType = (ParameterizedType) genericParameterType;
                    if (parameterizedType.getRawType().equals(Message.class)) {
                        genericParameterType = ((ParameterizedType) genericParameterType)
                                .getActualTypeArguments()[0];
                    } else if (parameterizedType.getRawType().equals(List.class)
                            && parameterizedType.getActualTypeArguments().length == 1) {
                        Type paramType = parameterizedType.getActualTypeArguments()[0];
                        this.isConsumerRecordList = paramType.equals(io.nats.client.Message.class)
                                || (paramType instanceof ParameterizedType && ((ParameterizedType) paramType)
                                        .getRawType().equals(io.nats.client.Message.class));
                        this.isMessageList = paramType.equals(Message.class)
                                || (paramType instanceof ParameterizedType
                                        && ((ParameterizedType) paramType).getRawType().equals(Message.class));
                    }
                }
            } else {
                if (this.logger.isDebugEnabled()) {
                    this.logger.debug("Ambiguous parameters for target payload for method " + method
                            + "; no inferred type available");
                }
                break;
            }
        }
    }
    Assert.state(!this.isConsumerRecordList || method.getParameterTypes().length == 1,
            "A parameter of type 'List<ConsumerRecord>' must be the only parameter");
    Assert.state(!this.isMessageList || method.getParameterTypes().length == 1,
            "A parameter of type 'List<Message<?>>' must be the only parameter");

    return genericParameterType;
}

From source file:com.basho.riak.client.api.commands.kv.UpdateValue.java

@SuppressWarnings("unchecked")
@Override//from  w  w  w .j  a v a  2  s.  c om
protected RiakFuture<Response, Location> executeAsync(final RiakCluster cluster) {
    final UpdateValueFuture updateFuture = new UpdateValueFuture(location);

    FetchValue.Builder fetchBuilder = new FetchValue.Builder(location);
    for (Map.Entry<FetchValue.Option<?>, Object> optPair : fetchOptions.entrySet()) {
        fetchBuilder.withOption((FetchValue.Option<Object>) optPair.getKey(), optPair.getValue());
    }

    RiakFuture<FetchValue.Response, Location> fetchFuture = fetchBuilder.build().executeAsync(cluster);

    // Anonymous listener that will do the work
    RiakFutureListener<FetchValue.Response, Location> fetchListener = new RiakFutureListener<FetchValue.Response, Location>() {
        @Override
        public void handle(RiakFuture<FetchValue.Response, Location> f) {
            if (f.isSuccess()) {
                FetchValue.Response fetchResponse;
                try {
                    fetchResponse = f.get();
                    Object resolved = null;
                    VClock vclock = null;

                    if (!fetchResponse.isNotFound()) {
                        if (typeReference == null) {
                            // Steal the type from the Update. Yes, Really.
                            ParameterizedType pType = (ParameterizedType) update.getClass()
                                    .getGenericSuperclass();
                            Type t = pType.getActualTypeArguments()[0];
                            if (t instanceof ParameterizedType) {
                                t = ((ParameterizedType) t).getRawType();
                            }

                            resolved = fetchResponse.getValue((Class<?>) t);
                        } else {
                            resolved = fetchResponse.getValue(typeReference);
                        }

                        // We get the vclock so we can inject it into the updated object. 
                        // This is so the end user doesn't have to worry about vclocks
                        // in the Update.
                        vclock = fetchResponse.getVectorClock();
                    }

                    Object updated = ((Update<Object>) update).apply(resolved);

                    if (update.isModified()) {
                        AnnotationUtil.setVClock(updated, vclock);

                        StoreValue.Builder store = new StoreValue.Builder(updated, typeReference)
                                .withLocation(location).withVectorClock(vclock);

                        for (Map.Entry<StoreValue.Option<?>, Object> optPair : storeOptions.entrySet()) {
                            store.withOption((StoreValue.Option<Object>) optPair.getKey(), optPair.getValue());
                        }
                        RiakFuture<StoreValue.Response, Location> storeFuture = store.build()
                                .executeAsync(cluster);
                        storeFuture.addListener(updateFuture);
                    } else {
                        Response updateResponse = new Response.Builder().withLocation(f.getQueryInfo())
                                .withUpdated(false).build();
                        updateFuture.setResponse(updateResponse);
                    }

                } catch (InterruptedException ex) {
                    updateFuture.setException(ex);
                } catch (UnresolvedConflictException ex) {
                    updateFuture.setException(ex);
                } catch (ConversionException ex) {
                    updateFuture.setException(ex);
                } catch (ExecutionException ex) {
                    updateFuture.setException(ex);
                }
            } else {
                updateFuture.setException(f.cause().getCause());
            }
        }
    };

    fetchFuture.addListener(fetchListener);
    return updateFuture;
}