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:net.firejack.platform.model.service.reverse.ReverseEngineeringService.java

private void analyzeField(String name, Type type, WebParam.Mode mode, boolean list, boolean holder,
        boolean _return, Service service) {
    if (type instanceof Class) {
        Class clazz = (Class) type;
        Parameter parameter = new Parameter(StringUtils.uncapitalize(name), clazz,
                clazz.isAnnotationPresent(XmlAccessorType.class), list, holder, mode);
        if (_return) {
            service.setReturn(parameter);
        } else {//from w w  w .j a  va  2 s . com
            service.addParameter(parameter);
        }
    } else if (type instanceof ParameterizedType) {
        ParameterizedType parameterizedType = (ParameterizedType) type;
        Type rawType = parameterizedType.getRawType();
        Type generic = parameterizedType.getActualTypeArguments()[0];
        if (rawType == Holder.class) {
            analyzeField(name, generic, mode, false, true, _return, service);
        } else if (rawType == List.class) {
            if (generic instanceof Class && ((Class) generic).isAnnotationPresent(XmlAccessorType.class)) {
                analyzeField(name, generic, mode, true, holder, _return, service);
            } else {
                analyzeField(name, rawType, mode, true, holder, _return, service);
            }
        } else {
            throw new IllegalStateException("Unknown type: " + type);
        }
    }
}

From source file:net.firejack.platform.model.service.reverse.ReverseEngineeringService.java

private void analyzeField(String name, Type type, RelationshipType relationshipType, EntityModel entityModel,
        XmlElement element, Map<String, EntityModel> models, List<RelationshipModel> relationships,
        List<FieldModel> fields) {
    if (type instanceof Class) {
        Class clazz = (Class) type;
        boolean required = false;
        if (element != null) {
            required = element.required();
            if (!name.equals(StringUtils.uncapitalize(element.name())) && !"##default".equals(element.name()))
                name = element.name();/*from w  w w. j  a v  a2  s.co m*/
        }

        if (clazz.isAnnotationPresent(XmlAccessorType.class)) {
            EntityModel target = createBeanEntity(clazz, entityModel.getParent(), relationships, models);
            RelationshipModel relationshipModel = createRelationship(name, required, entityModel, target,
                    relationshipType);
            relationships.add(relationshipModel);
        } else {
            FieldModel field = createField(name, clazz, required, entityModel);
            fields.add(field);
        }
    } else if (type instanceof ParameterizedType) {
        ParameterizedType parameterizedType = (ParameterizedType) type;
        Type rawType = parameterizedType.getRawType();
        Type generic = parameterizedType.getActualTypeArguments()[0];
        if (rawType == Holder.class) {
            analyzeField(name, generic, relationshipType, entityModel, element, models, relationships, fields);
        } else if (rawType == List.class) {
            if (generic instanceof Class && ((Class) generic).isAnnotationPresent(XmlAccessorType.class)) {
                analyzeField(name, generic, ASSOCIATION, entityModel, element, models, relationships, fields);
            } else {
                analyzeField(name, rawType, relationshipType, entityModel, element, models, relationships,
                        fields);
            }
        } else {
            throw new IllegalStateException("Unknown type: " + type + " entity: " + entityModel.getName());
        }
    }
}

From source file:dinistiq.Dinistiq.java

/**
 * Tries to resolve the value for a given placeholder.
 *
 * @param beanProperties properties of the beans to resolve the value for
 * @param dependencies global dependencies collector to store retrieved reference values as dependecy in
 * @param customer "customer" descriptor for logging who needed the value resolved
 * @param cls target class of the value// w w w.  j  a  va2 s .c  o m
 * @param type target type of the value
 * @param name name of the placeholder
 * @return replaced value or original string
 * @throws Exception
 */
private Object getValue(Properties beanProperties, Map<String, Set<Object>> dependencies, String customer,
        Class<?> cls, Type type, final String name) throws Exception {
    ParameterizedType parameterizedType = (type instanceof ParameterizedType) ? (ParameterizedType) type : null;
    if ((name == null) && Collection.class.isAssignableFrom(cls)) {
        LOG.debug("getValue() collection: {}", type);
        if (parameterizedType != null) {
            Type collectionType = parameterizedType.getActualTypeArguments()[0];
            LOG.debug("getValue() inner type {}", collectionType);
            Collection<? extends Object> resultCollection = findBeans((Class<? extends Object>) collectionType);
            resultCollection = List.class.isAssignableFrom(cls) ? new ArrayList<>(resultCollection)
                    : resultCollection;
            if (dependencies != null) {
                dependencies.get(customer).addAll(resultCollection);
            } // if
            return resultCollection;
        } // if
    } // if
    Object bean = (name == null) ? findBean(cls)
            : (beanProperties.containsKey(name) ? getReferenceValue(beanProperties.getProperty(name))
                    : beans.get(name));
    if (Provider.class.equals(cls)) {
        final Dinistiq d = this;
        final Class<? extends Object> c = (Class<?>) parameterizedType.getActualTypeArguments()[0];
        LOG.info("getValue() Provider for {} :{}", name, c);
        bean = new Provider<Object>() {

            @Override
            public Object get() {
                return (name == null) ? d.findBean(c) : d.findBean(c, name);
            }

        };
        String beanName = "" + bean;
        if (dependencies != null) {
            dependencies.put(beanName, new HashSet<>());
        } // if
        beans.put(beanName, bean);
    } // if
    if (cls.isAssignableFrom(bean.getClass())) {
        if ((dependencies != null) && beans.containsValue(bean)) {
            dependencies.get(customer).add(bean);
        } // if
        return bean;
    } // if
    throw new Exception("for " + customer + ": no bean " + (name != null ? name + " :" : "of type ")
            + cls.getSimpleName() + " found.");
}

From source file:org.romaframework.core.schema.SchemaHelper.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public static Class<?> resolveClassFromType(Type type, ParameterizedType params) {
    if (type instanceof Class<?>)
        return (Class<?>) type;
    if (type instanceof ParameterizedType) {
        return resolveClassFromType(((ParameterizedType) type).getRawType(), (ParameterizedType) type);
    }//from w  ww.ja v  a 2s.c o  m
    if (type instanceof GenericArrayType) {
        GenericArrayType gat = (GenericArrayType) type;
        Class<?> arrItemp = resolveClassFromType(gat.getGenericComponentType(), null);
        return Array.newInstance(arrItemp, 0).getClass();
    }
    if (type instanceof TypeVariable<?>) {
        TypeVariable<?> t = (TypeVariable<?>) type;
        if (params != null) {
            Class<?> cl = resolveClassFromType(params.getRawType(), null);
            if (cl != null) {

                TypeVariable<Class<?>>[] var = ((Class) cl).getTypeParameters();
                int i = 0;
                for (; i < var.length; i++) {
                    if (var[i].getName().equals(t.getName())) {
                        return resolveClassFromType(params.getActualTypeArguments()[i],
                                resolveParameterizedType(params.getOwnerType()));
                    }
                }
            }
        }
        Type[] bounds = t.getBounds();
        if (bounds.length == 1)
            return resolveClassFromType(bounds[0], params);
    }
    if (type instanceof WildcardType) {
        // TODO:
    }
    return null;
}

From source file:org.broadinstitute.gatk.utils.help.GenericDocumentationHandler.java

/**
 * Helper routine that returns the Feature.class required by a RodBinding,
 * either T for RodBinding{T} or List{RodBinding{T}}.  Returns null if
 * the Type doesn't fit either model./* ww w  .  ja  v a  2 s  . c o  m*/
 *
 * @param type
 * @return
 */
protected Class<? extends Feature> getFeatureTypeIfPossible(Type type) {
    if (type instanceof ParameterizedType) {
        ParameterizedType paramType = (ParameterizedType) type;
        if (RodBinding.class.isAssignableFrom((Class<?>) paramType.getRawType())) {
            return (Class<? extends Feature>) JVMUtils.getParameterizedTypeClass(type);
        } else {
            for (Type paramtype : paramType.getActualTypeArguments()) {
                Class<? extends Feature> x = getFeatureTypeIfPossible(paramtype);
                if (x != null)
                    return x;
            }
        }
    }

    return null;
}

From source file:jp.terasoluna.fw.util.GenericsUtil.java

/**
 * ??<code>Type</code>??/* ww w  .j av  a 2  s. c o  m*/
 * @param type ????<code>Type</code>
 * @param ancestorTypeList <code>type</code>??? ??????<code>ParameterizedType</code>?
 * @return ?
 * @throws IllegalStateException <code>type</code>? <code>Class</code>???? <code>TypeVariable</code>????? 
 *             <code>type</code>?? ????????? <code>type</code>???<code>Class</code>????
 *             (??)?
 */
protected static Class<? extends Object> resolveTypeVariable(Type type,
        List<ParameterizedType> ancestorTypeList) throws IllegalStateException {

    if (isNotTypeVariable(type)) {
        return getRawClass(type);
    }

    // TypeVariable:?
    TypeVariable<?> targetType = (TypeVariable<?>) type;
    Type actualType = null;
    for (int i = ancestorTypeList.size() - 1; i >= 0; i--) {
        ParameterizedType ancestorType = ancestorTypeList.get(i);

        // ?????
        GenericDeclaration declaration = targetType.getGenericDeclaration();
        if (!(declaration instanceof Class)) {
            throw new IllegalStateException("TypeVariable(" + targetType.getName()
                    + " is not declared at Class " + "(ie. is declared at Method or Constructor)");
        }

        // ?Generics????????
        Class<?> declaredClass = (Class<?>) declaration;
        if (declaredClass != ancestorType.getRawType()) {
            continue;
        }

        // ????????
        // ConcreteAbstractBLogic<R,P> extends AbstractBLogic<P,R>
        // ????????type????
        Type[] parameterTypes = declaredClass.getTypeParameters();
        int index = ArrayUtils.indexOf(parameterTypes, targetType);
        if (index == -1) {
            // ???????????????
            // ??????????
            // ???Generics?API?????????????
            // ?????????
            throw new IllegalStateException("Class(" + declaredClass.getName()
                    + ") does not declare TypeValidable(" + targetType.getName() + ")");
        }
        actualType = ancestorType.getActualTypeArguments()[index];
        if (log.isDebugEnabled()) {
            log.debug("resolved " + targetType.getName() + " -> " + actualType);
        }

        if (isNotTypeVariable(actualType)) {
            return getRawClass(actualType);
        }
        targetType = (TypeVariable<?>) actualType;
    }

    throw new IllegalStateException(
            "Concrete type of Type(" + type + ") was not found in ancestorList(" + ancestorTypeList + ")");
}

From source file:org.sleeksnap.ScreenSnapper.java

/**
 * Attempt to get the upload type from the Superclass
 * /*from w  w w. ja  v  a  2  s.  c om*/
 * @param uploader
 *            The uploader to get the type from
 * @return The type
 */
@SuppressWarnings("unchecked")
public Class<? extends Upload> getUploaderType(final Uploader<? extends Upload> uploader) {
    // Find the uploader type
    final ParameterizedType parameterizedType = (ParameterizedType) uploader.getClass().getGenericSuperclass();
    final Type[] args = parameterizedType.getActualTypeArguments();
    if (args.length == 0) {
        throw new RuntimeException("Uploader does not include a valid type");
    }
    return (Class<? extends Upload>) args[0];
}

From source file:org.optaplanner.core.impl.domain.solution.descriptor.SolutionDescriptor.java

public ScoreDefinition buildScoreDefinition(Class<? extends Score> scoreType, PlanningScore annotation) {
    Class<? extends ScoreDefinition> scoreDefinitionClass = annotation.scoreDefinitionClass();
    if (scoreDefinitionClass != PlanningScore.NullScoreDefinition.class) {
        if (annotation.bendableHardLevelsSize() != PlanningScore.NO_LEVEL_SIZE
                || annotation.bendableSoftLevelsSize() != PlanningScore.NO_LEVEL_SIZE) {
            throw new IllegalArgumentException("The solutionClass (" + solutionClass + ") has a "
                    + PlanningScore.class.getSimpleName() + " annotated member (" + scoreMemberAccessor
                    + ") that has a scoreDefinition (" + scoreDefinitionClass
                    + ") that must not have a bendableHardLevelsSize (" + annotation.bendableHardLevelsSize()
                    + ") or a bendableSoftLevelsSize (" + annotation.bendableSoftLevelsSize() + ").");
        }//from www  . j a  va 2s . co m
        return ConfigUtils.newInstance(this, "scoreDefinitionClass", scoreDefinitionClass);
    }
    if (scoreType == Score.class) {
        if (!AbstractSolution.class.isAssignableFrom(solutionClass)) {
            throw new IllegalStateException("The solutionClass (" + solutionClass + ") has a "
                    + PlanningScore.class.getSimpleName() + " annotated member (" + scoreMemberAccessor
                    + ") that doesn't return a non-abstract " + Score.class.getSimpleName() + " class.\n"
                    + "Maybe make it return " + HardSoftScore.class.getSimpleName() + " or another specific "
                    + Score.class.getSimpleName() + " implementation.");
        } else {
            // Magic to support AbstractSolution
            if (solutionClass == AbstractSolution.class) {
                throw new IllegalArgumentException(
                        "The solutionClass (" + solutionClass + ") cannot be directly a "
                                + AbstractSolution.class.getSimpleName() + ", but a subclass would be ok.");
            }
            Class<?> baseClass = solutionClass;
            while (baseClass.getSuperclass() != AbstractSolution.class) {
                baseClass = baseClass.getSuperclass();
                if (baseClass == null) {
                    throw new IllegalStateException(
                            "Impossible situation because the solutionClass (" + solutionClass
                                    + ") is assignable from " + AbstractSolution.class.getSimpleName() + ".");
                }
            }
            Type genericAbstractSolution = solutionClass.getGenericSuperclass();
            if (!(genericAbstractSolution instanceof ParameterizedType)) {
                throw new IllegalStateException("Impossible situation because the genericAbstractSolution ("
                        + genericAbstractSolution + ") is a " + AbstractSolution.class.getSimpleName() + ".");
            }
            ParameterizedType parameterizedAbstractSolution = (ParameterizedType) genericAbstractSolution;
            Type[] typeArguments = parameterizedAbstractSolution.getActualTypeArguments();
            if (typeArguments.length != 1) {
                throw new IllegalStateException(
                        "Impossible situation because the parameterizedAbstractSolution ("
                                + parameterizedAbstractSolution + ") is a "
                                + AbstractSolution.class.getSimpleName() + ".");
            }
            Type typeArgument = typeArguments[0];
            if (!(typeArgument instanceof Class)) {
                throw new IllegalStateException("Impossible situation because a ("
                        + AbstractSolution.class.getSimpleName() + "'s typeArgument (" + typeArgument
                        + ") must be a " + Score.class.getSimpleName() + ".");
            }
            scoreType = (Class<? extends Score>) typeArgument;
        }
    }
    if (!AbstractBendableScore.class.isAssignableFrom(scoreType)) {
        if (annotation.bendableHardLevelsSize() != PlanningScore.NO_LEVEL_SIZE
                || annotation.bendableSoftLevelsSize() != PlanningScore.NO_LEVEL_SIZE) {
            throw new IllegalArgumentException("The solutionClass (" + solutionClass + ") has a "
                    + PlanningScore.class.getSimpleName() + " annotated member (" + scoreMemberAccessor
                    + ") that returns a scoreType (" + scoreType
                    + ") that must not have a bendableHardLevelsSize (" + annotation.bendableHardLevelsSize()
                    + ") or a bendableSoftLevelsSize (" + annotation.bendableSoftLevelsSize() + ").");
        }
        if (scoreType.equals(SimpleScore.class)) {
            return new SimpleScoreDefinition();
        } else if (scoreType.equals(SimpleLongScore.class)) {
            return new SimpleLongScoreDefinition();
        } else if (scoreType.equals(SimpleDoubleScore.class)) {
            return new SimpleDoubleScoreDefinition();
        } else if (scoreType.equals(SimpleBigDecimalScore.class)) {
            return new SimpleBigDecimalScoreDefinition();
        } else if (scoreType.equals(HardSoftScore.class)) {
            return new HardSoftScoreDefinition();
        } else if (scoreType.equals(HardSoftLongScore.class)) {
            return new HardSoftLongScoreDefinition();
        } else if (scoreType.equals(HardSoftDoubleScore.class)) {
            return new HardSoftDoubleScoreDefinition();
        } else if (scoreType.equals(HardSoftBigDecimalScore.class)) {
            return new HardSoftBigDecimalScoreDefinition();
        } else if (scoreType.equals(HardMediumSoftScore.class)) {
            return new HardMediumSoftScoreDefinition();
        } else if (scoreType.equals(HardMediumSoftLongScore.class)) {
            return new HardMediumSoftLongScoreDefinition();
        } else {
            throw new IllegalArgumentException("The solutionClass (" + solutionClass + ") has a "
                    + PlanningScore.class.getSimpleName() + " annotated member (" + scoreMemberAccessor
                    + ") that returns a scoreType (" + scoreType + ") that is not recognized as a default "
                    + Score.class.getSimpleName() + " implementation.\n"
                    + "  If you intend to use a custom implementation," + " maybe set a scoreDefinition in the "
                    + PlanningScore.class.getSimpleName() + " annotation.");
        }
    } else {
        int bendableHardLevelsSize = annotation.bendableHardLevelsSize();
        int bendableSoftLevelsSize = annotation.bendableSoftLevelsSize();
        if (bendableHardLevelsSize == PlanningScore.NO_LEVEL_SIZE
                || bendableSoftLevelsSize == PlanningScore.NO_LEVEL_SIZE) {
            throw new IllegalArgumentException("The solutionClass (" + solutionClass + ") has a "
                    + PlanningScore.class.getSimpleName() + " annotated member (" + scoreMemberAccessor
                    + ") that returns a scoreType (" + scoreType + ") that must have a bendableHardLevelsSize ("
                    + annotation.bendableHardLevelsSize() + ") and a bendableSoftLevelsSize ("
                    + annotation.bendableSoftLevelsSize() + ").");
        }
        if (scoreType.equals(BendableScore.class)) {
            return new BendableScoreDefinition(bendableHardLevelsSize, bendableSoftLevelsSize);
        } else if (scoreType.equals(BendableLongScore.class)) {
            return new BendableLongScoreDefinition(bendableHardLevelsSize, bendableSoftLevelsSize);
        } else if (scoreType.equals(BendableBigDecimalScore.class)) {
            return new BendableBigDecimalScoreDefinition(bendableHardLevelsSize, bendableSoftLevelsSize);
        } else {
            throw new IllegalArgumentException("The solutionClass (" + solutionClass + ") has a "
                    + PlanningScore.class.getSimpleName() + " annotated member (" + scoreMemberAccessor
                    + ") that returns a bendable scoreType (" + scoreType
                    + ") that is not recognized as a default " + Score.class.getSimpleName()
                    + " implementation.\n" + "  If you intend to use a custom implementation,"
                    + " maybe set a scoreDefinition in the annotation.");
        }
    }
}

From source file:org.apache.sling.models.impl.ModelAdapterFactory.java

private Result<Object> adaptIfNecessary(final Object value, final Class<?> type, final Type genericType) {
    final Object adaptedValue;
    if (!isAcceptableType(type, genericType, value)) {
        if (isModelClass(value, type) && canCreateFromAdaptable(value, type)) {
            Result<?> result = internalCreateModel(value, type);
            if (result.wasSuccessful()) {
                adaptedValue = result.getValue();
            } else {
                return new Result<Object>(
                        new ModelClassException(String.format("Could not create model from %s: %s",
                                value.getClass(), result.getThrowable().getMessage()), result.getThrowable()));
            }/*from   ww w. j av a  2s . c o  m*/
        } else if (value instanceof Adaptable) {
            adaptedValue = ((Adaptable) value).adaptTo(type);
            if (adaptedValue == null) {
                return new Result<Object>(new ModelClassException(
                        String.format("Could not adapt from %s to %s", value.getClass(), type)));
            }
        } else if (genericType instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) genericType;
            if (value instanceof Collection && (type.equals(Collection.class) || type.equals(List.class))
                    && parameterizedType.getActualTypeArguments().length == 1) {
                List<Object> result = new ArrayList<Object>();
                for (Object valueObject : (Collection<?>) value) {
                    if (valueObject instanceof Adaptable) {
                        Object adapted = ((Adaptable) valueObject)
                                .adaptTo((Class<?>) parameterizedType.getActualTypeArguments()[0]);
                        if (adapted != null) {
                            result.add(adapted);
                        } else {
                            return new Result<Object>(new ModelClassException(
                                    String.format("Could not adapt from %s to %s within the collection",
                                            value.getClass(), type)));
                        }
                    }
                }
                adaptedValue = result;
            } else {
                return new Result<Object>(new ModelClassException(
                        String.format("%s is neither a parametrized Collection or List", type)));
            }
        } else {
            return new Result<Object>(new ModelClassException(
                    String.format("Could not adapt from %s to %s, because this class is not adaptable!",
                            value.getClass(), type)));
        }
        return new Result<Object>(adaptedValue);
    } else {
        return new Result<Object>(value);
    }
}

From source file:com.evolveum.midpoint.prism.parser.PrismBeanConverter.java

private Type getTypeArgument(Type origType, String desc) {
    if (!(origType instanceof ParameterizedType)) {
        throw new IllegalArgumentException("No a parametrized type " + desc);
    }//from  www. ja  va2  s  .co m
    ParameterizedType parametrizedType = (ParameterizedType) origType;
    Type[] actualTypeArguments = parametrizedType.getActualTypeArguments();
    if (actualTypeArguments == null || actualTypeArguments.length == 0) {
        throw new IllegalArgumentException("No type arguments for getter " + desc);
    }
    if (actualTypeArguments.length > 1) {
        throw new IllegalArgumentException("Too many type arguments for getter for " + desc);
    }
    return actualTypeArguments[0];
}