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:org.broadleafcommerce.openadmin.server.dao.provider.metadata.CollectionFieldMetadataProvider.java

protected void buildCollectionMetadata(Class<?> parentClass, Class<?> targetClass,
        Map<String, FieldMetadata> attributes, FieldInfo field, FieldMetadataOverride collectionMetadata,
        String prefix) {// ww w. jav  a2s.  co m
    BasicCollectionMetadata serverMetadata = (BasicCollectionMetadata) attributes.get(field.getName());

    Class<?> resolvedClass = parentClass == null ? targetClass : parentClass;
    BasicCollectionMetadata metadata;
    if (serverMetadata != null) {
        metadata = serverMetadata;
    } else {
        metadata = new BasicCollectionMetadata();
    }
    metadata.setTargetClass(targetClass.getName());
    metadata.setFieldName(field.getName());
    if (collectionMetadata.getReadOnly() != null) {
        metadata.setMutable(!collectionMetadata.getReadOnly());
    }
    if (collectionMetadata.getAddMethodType() != null) {
        metadata.setAddMethodType(collectionMetadata.getAddMethodType());
    }
    if (collectionMetadata.getShowIfProperty() != null) {
        metadata.setShowIfProperty(collectionMetadata.getShowIfProperty());
    }

    org.broadleafcommerce.openadmin.dto.OperationTypes dtoOperationTypes = new org.broadleafcommerce.openadmin.dto.OperationTypes(
            OperationType.BASIC, OperationType.BASIC, OperationType.BASIC, OperationType.BASIC,
            OperationType.BASIC);
    if (collectionMetadata.getAddType() != null) {
        dtoOperationTypes.setAddType(collectionMetadata.getAddType());
    }
    if (collectionMetadata.getRemoveType() != null) {
        dtoOperationTypes.setRemoveType(collectionMetadata.getRemoveType());
    }
    if (collectionMetadata.getFetchType() != null) {
        dtoOperationTypes.setFetchType(collectionMetadata.getFetchType());
    }
    if (collectionMetadata.getInspectType() != null) {
        dtoOperationTypes.setInspectType(collectionMetadata.getInspectType());
    }
    if (collectionMetadata.getUpdateType() != null) {
        dtoOperationTypes.setUpdateType(collectionMetadata.getUpdateType());
    }

    if (AddMethodType.LOOKUP == metadata.getAddMethodType()) {
        dtoOperationTypes.setRemoveType(OperationType.NONDESTRUCTIVEREMOVE);
    }

    //don't allow additional non-persistent properties or additional foreign keys for an advanced collection datasource - they don't make sense in this context
    PersistencePerspective persistencePerspective;
    if (serverMetadata != null) {
        persistencePerspective = metadata.getPersistencePerspective();
        persistencePerspective.setOperationTypes(dtoOperationTypes);
    } else {
        persistencePerspective = new PersistencePerspective(dtoOperationTypes, new String[] {},
                new ForeignKey[] {});
        metadata.setPersistencePerspective(persistencePerspective);
    }

    String foreignKeyName = null;
    if (serverMetadata != null) {
        foreignKeyName = ((ForeignKey) serverMetadata.getPersistencePerspective()
                .getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.FOREIGNKEY))
                        .getManyToField();
    }
    if (!StringUtils.isEmpty(collectionMetadata.getManyToField())) {
        foreignKeyName = collectionMetadata.getManyToField();
    }
    if (foreignKeyName == null && !StringUtils.isEmpty(field.getOneToManyMappedBy())) {
        foreignKeyName = field.getOneToManyMappedBy();
    }
    if (foreignKeyName == null && !StringUtils.isEmpty(field.getManyToManyMappedBy())) {
        foreignKeyName = field.getManyToManyMappedBy();
    }
    if (StringUtils.isEmpty(foreignKeyName)) {
        throw new IllegalArgumentException(
                "Unable to infer a ManyToOne field name for the @AdminPresentationCollection annotated field("
                        + field.getName()
                        + "). If not using the mappedBy property of @OneToMany or @ManyToMany, please make sure to explicitly define the manyToField property");
    }

    String sortProperty = null;
    if (serverMetadata != null) {
        sortProperty = ((ForeignKey) serverMetadata.getPersistencePerspective().getPersistencePerspectiveItems()
                .get(PersistencePerspectiveItemType.FOREIGNKEY)).getSortField();
    }
    if (!StringUtils.isEmpty(collectionMetadata.getSortProperty())) {
        sortProperty = collectionMetadata.getSortProperty();
    }

    Boolean isAscending = true;
    if (serverMetadata != null) {
        isAscending = ((ForeignKey) serverMetadata.getPersistencePerspective().getPersistencePerspectiveItems()
                .get(PersistencePerspectiveItemType.FOREIGNKEY)).getSortAscending();
    }
    if (collectionMetadata.isSortAscending() != null) {
        isAscending = collectionMetadata.isSortAscending();
    }

    if (serverMetadata != null) {
        ForeignKey foreignKey = (ForeignKey) metadata.getPersistencePerspective()
                .getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.FOREIGNKEY);
        foreignKey.setManyToField(foreignKeyName);
        foreignKey.setForeignKeyClass(resolvedClass.getName());
        foreignKey.setMutable(metadata.isMutable());
        foreignKey.setOriginatingField(prefix + field.getName());
        foreignKey.setSortField(sortProperty);
        foreignKey.setSortAscending(isAscending);
    } else {
        ForeignKey foreignKey = new ForeignKey(foreignKeyName, resolvedClass.getName(), null,
                ForeignKeyRestrictionType.ID_EQ);
        foreignKey.setMutable(metadata.isMutable());
        foreignKey.setOriginatingField(prefix + field.getName());
        foreignKey.setSortField(sortProperty);
        foreignKey.setSortAscending(isAscending);
        persistencePerspective.addPersistencePerspectiveItem(PersistencePerspectiveItemType.FOREIGNKEY,
                foreignKey);
    }

    String ceiling = null;
    checkCeiling: {
        if (field.getGenericType() instanceof ParameterizedType) {
            try {
                ParameterizedType pt = (ParameterizedType) field.getGenericType();
                java.lang.reflect.Type collectionType = pt.getActualTypeArguments()[0];
                String ceilingEntityName = ((Class<?>) collectionType).getName();
                ceiling = entityConfiguration.lookupEntityClass(ceilingEntityName).getName();
                break checkCeiling;
            } catch (NoSuchBeanDefinitionException e) {
                // We weren't successful at looking at entity configuration to find the type of this collection.
                // We will continue and attempt to find it via the Hibernate annotations
            }
        }
        if (!StringUtils.isEmpty(field.getOneToManyTargetEntity())
                && !void.class.getName().equals(field.getOneToManyTargetEntity())) {
            ceiling = field.getOneToManyTargetEntity();
            break checkCeiling;
        }
        if (!StringUtils.isEmpty(field.getManyToManyTargetEntity())
                && !void.class.getName().equals(field.getManyToManyTargetEntity())) {
            ceiling = field.getManyToManyTargetEntity();
            break checkCeiling;
        }
    }
    if (!StringUtils.isEmpty(ceiling)) {
        metadata.setCollectionCeilingEntity(ceiling);
    }

    if (collectionMetadata.getExcluded() != null) {
        if (LOG.isDebugEnabled()) {
            if (collectionMetadata.getExcluded()) {
                LOG.debug("buildCollectionMetadata:Excluding " + field.getName()
                        + " because it was explicitly declared in config");
            } else {
                LOG.debug("buildCollectionMetadata:Showing " + field.getName()
                        + " because it was explicitly declared in config");
            }
        }
        metadata.setExcluded(collectionMetadata.getExcluded());
    }
    if (collectionMetadata.getFriendlyName() != null) {
        metadata.setFriendlyName(collectionMetadata.getFriendlyName());
    }
    if (collectionMetadata.getSecurityLevel() != null) {
        metadata.setSecurityLevel(collectionMetadata.getSecurityLevel());
    }
    if (collectionMetadata.getOrder() != null) {
        metadata.setOrder(collectionMetadata.getOrder());
    }

    if (collectionMetadata.getTab() != null) {
        metadata.setTab(collectionMetadata.getTab());
    }
    if (collectionMetadata.getTabOrder() != null) {
        metadata.setTabOrder(collectionMetadata.getTabOrder());
    }

    if (collectionMetadata.getSortProperty() != null) {
        metadata.setSortProperty(collectionMetadata.getSortProperty());
    }

    if (collectionMetadata.getCustomCriteria() != null) {
        metadata.setCustomCriteria(collectionMetadata.getCustomCriteria());
    }

    if (collectionMetadata.getUseServerSideInspectionCache() != null) {
        persistencePerspective
                .setUseServerSideInspectionCache(collectionMetadata.getUseServerSideInspectionCache());
    }

    if (collectionMetadata.getCurrencyCodeField() != null) {
        metadata.setCurrencyCodeField(collectionMetadata.getCurrencyCodeField());
    }

    attributes.put(field.getName(), metadata);
}

From source file:com.googlecode.jdbcproc.daofactory.impl.block.service.ParametersSetterBlockServiceImpl.java

private Class getListEntityClass(Type type) {
    ParameterizedType parameterizedType = (ParameterizedType) type;
    return (Class) parameterizedType.getActualTypeArguments()[0];
}

From source file:org.appverse.web.framework.backend.rest.services.integration.impl.live.RestPersistenceService.java

/**
 * Use reflection to get the actual generic type
 * /*from   w w  w  . j av a  2s . co  m*/
 * @return
 * @throws Exception
 */
@SuppressWarnings("unchecked")
protected Class<T> getClassP() throws Exception {
    Method method = this.getClass().getMethod("getTypeSafeList");

    Type returnType = method.getGenericReturnType();
    Class<T> classP = null;

    if (returnType instanceof ParameterizedType) {
        ParameterizedType type = (ParameterizedType) returnType;
        Type[] typeArguments = type.getActualTypeArguments();
        for (Type typeArgument : typeArguments) {
            classP = (Class<T>) typeArgument;
            System.out.println("typeArgClass = " + classP);
        }
    }
    return classP;

}

From source file:org.evosuite.utils.TestGenericClass.java

@Test
public void testGenericInstantiationMapType() throws ConstructionFailedException {
    GenericClass genericClass = new GenericClass(
            com.examples.with.different.packagename.generic.GenericParameterExtendingGenericBounds.class);
    GenericClass instantiatedClass = genericClass.getGenericInstantiation();
    //GenericClass instantiatedClass = linkedlistOfTypeVariable.getGenericInstantiation(listOfInteger.getTypeVariableMap());
    System.out.println(instantiatedClass.toString());
    Type parameterType = instantiatedClass.getParameterTypes().get(0);
    Assert.assertTrue(TypeUtils.isAssignable(parameterType, Map.class));
    Assert.assertTrue(parameterType instanceof ParameterizedType);

    ParameterizedType parameterizedType = (ParameterizedType) parameterType;
    Assert.assertEquals(String.class, parameterizedType.getActualTypeArguments()[0]);
}

From source file:org.raml.emitter.RamlEmitterV2.java

@SuppressWarnings("rawtypes")
private void generateSequenceOfMaps(StringBuilder dump, int depth, List seq, ParameterizedType itemType) {
    Type rawType = itemType.getRawType();
    if (rawType instanceof Class && Map.class.isAssignableFrom((Class<?>) rawType)) {
        Type valueType = itemType.getActualTypeArguments()[1];
        if (valueType instanceof Class) {
            dump.append("\n");//TODO REVIEW
            for (Object item : seq) {
                dump.append(indent(depth)).append(YAML_SEQ);
                dumpMap(dump, depth + 1, valueType, (Map) item, false, true);
            }/*w  w  w.  ja  v  a2 s.c  o  m*/
        }
    }
}

From source file:com.prepaird.objectgraphdb.ObjectGraphDb.java

private <E> Class<E> getCollectionGenericType(Field f) {
    //since this is an iterable we actually need the generic type of the iterable
    //see http://stackoverflow.com/questions/1942644/get-generic-type-of-java-util-list 
    Type type = f.getGenericType();
    if (type instanceof ParameterizedType) {
        ParameterizedType paramType = (ParameterizedType) type;
        return paramType.getActualTypeArguments().length > 0 ? (Class<E>) paramType.getActualTypeArguments()[0]
                : null;//  w  w w .j a v a  2s  . co m
    } else if (type instanceof Class) {
        return (Class) type;
    } else {
        Log.error("cannot determine type of " + type.getTypeName());
        return null;
    }
}

From source file:com.meidusa.venus.client.RemotingInvocationHandler.java

protected Object invokeRemoteService(Service service, Endpoint endpoint, Method method,
        EndpointParameter[] params, Object[] args) throws Exception {
    String apiName = VenusAnnotationUtils.getApiname(method, service, endpoint);

    AthenaTransactionId athenaTransactionId = null;
    if (service.athenaFlag()) {
        athenaTransactionId = AthenaTransactionDelegate.getDelegate().startClientTransaction(apiName);
    }/*w  w w  .  j  a  v  a2 s .  c  om*/
    boolean async = false;

    if (endpoint.async()) {
        async = true;
    }

    byte[] traceID = VenusTracerUtil.getTracerID();

    if (traceID == null) {
        traceID = VenusTracerUtil.randomTracerID();
    }

    Serializer serializer = SerializerFactory.getSerializer(serializeType);

    SerializeServiceRequestPacket serviceRequestPacket = new SerializeServiceRequestPacket(serializer, null);

    serviceRequestPacket.clientId = PacketConstant.VENUS_CLIENT_ID;
    serviceRequestPacket.clientRequestId = sequenceId.getAndIncrement();
    serviceRequestPacket.traceId = traceID;
    serviceRequestPacket.apiName = apiName;
    serviceRequestPacket.serviceVersion = service.version();
    serviceRequestPacket.parameterMap = new HashMap<String, Object>();

    if (params != null) {
        for (int i = 0; i < params.length; i++) {
            if (args[i] instanceof InvocationListener) {
                async = true;
                ReferenceInvocationListener listener = new ReferenceInvocationListener();
                ServicePacketBuffer buffer = new ServicePacketBuffer(16);
                buffer.writeLengthCodedString(args[i].getClass().getName(), "utf-8");
                buffer.writeInt(System.identityHashCode(args[i]));
                listener.setIdentityData(buffer.toByteBuffer().array());
                Type type = method.getGenericParameterTypes()[i];
                if (type instanceof ParameterizedType) {
                    ParameterizedType genericType = ((ParameterizedType) type);
                    container.putInvocationListener((InvocationListener) args[i],
                            genericType.getActualTypeArguments()[0]);
                } else {
                    throw new InvalidParameterException("invocationListener is not generic");
                }

                serviceRequestPacket.parameterMap.put(params[i].getParamName(), listener);
            } else {
                serviceRequestPacket.parameterMap.put(params[i].getParamName(), args[i]);
            }

        }
    }
    setTransactionId(serviceRequestPacket, athenaTransactionId);

    PerformanceLevel pLevel = AnnotationUtil.getAnnotation(method.getAnnotations(), PerformanceLevel.class);
    long start = TimeUtil.currentTimeMillis();
    long borrowed = start;

    if (async) {
        if (!this.isEnableAsync()) {
            throw new VenusConfigException("service async call disabled");
        }

        BackendConnection conn = null;
        try {

            if (nioConnPool instanceof RequestLoadbalanceObjectPool) {
                conn = (BackendConnection) ((RequestLoadbalanceObjectPool) nioConnPool)
                        .borrowObject(serviceRequestPacket.parameterMap, endpoint);
            } else {
                conn = nioConnPool.borrowObject();
            }
            borrowed = TimeUtil.currentTimeMillis();

            conn.write(serviceRequestPacket.toByteBuffer());
            VenusTracerUtil.logRequest(traceID, serviceRequestPacket.apiName,
                    JSON.toJSONString(serviceRequestPacket.parameterMap, JSON_FEATURE));
            return null;
        } finally {
            if (service.athenaFlag()) {
                AthenaTransactionDelegate.getDelegate().completeClientTransaction();
            }
            if (performanceLogger.isDebugEnabled()) {
                long end = TimeUtil.currentTimeMillis();
                long time = end - borrowed;
                StringBuffer buffer = new StringBuffer();
                buffer.append("[").append(borrowed - start).append(",").append(time)
                        .append("]ms (*client,async*) traceID=").append(UUID.toString(traceID)).append(", api=")
                        .append(serviceRequestPacket.apiName);

                performanceLogger.debug(buffer.toString());
            }

            if (conn != null) {
                nioConnPool.returnObject(conn);
            }
        }
    } else {
        AbstractBIOConnection conn = null;
        int soTimeout = 0;
        int oldTimeout = 0;
        boolean success = true;
        int errorCode = 0;
        AbstractServicePacket packet = null;
        String remoteAddress = null;
        boolean invalided = false;
        try {
            if (bioConnPool instanceof RequestLoadbalanceObjectPool) {
                conn = (AbstractBIOConnection) ((RequestLoadbalanceObjectPool) bioConnPool)
                        .borrowObject(serviceRequestPacket.parameterMap, endpoint);
            } else {
                conn = (AbstractBIOConnection) bioConnPool.borrowObject();
            }
            remoteAddress = conn.getRemoteAddress();
            borrowed = TimeUtil.currentTimeMillis();
            ServiceConfig config = this.serviceFactory.getServiceConfig(method.getDeclaringClass());

            oldTimeout = conn.getSoTimeout();
            if (config != null) {
                EndpointConfig endpointConfig = config.getEndpointConfig(endpoint.name());
                if (endpointConfig != null) {
                    int eTimeOut = endpointConfig.getTimeWait();
                    if (eTimeOut > 0) {
                        soTimeout = eTimeOut;
                    }
                } else {
                    if (config.getTimeWait() > 0) {
                        soTimeout = config.getTimeWait();
                    } else {
                        if (endpoint.timeWait() > 0) {
                            soTimeout = endpoint.timeWait();
                        }
                    }
                }

            } else {

                if (endpoint.timeWait() > 0) {
                    soTimeout = endpoint.timeWait();
                }
            }

            byte[] bts;

            try {

                if (soTimeout > 0) {
                    conn.setSoTimeout(soTimeout);
                }
                conn.write(serviceRequestPacket.toByteArray());
                VenusTracerUtil.logRequest(traceID, serviceRequestPacket.apiName,
                        JSON.toJSONString(serviceRequestPacket.parameterMap, JSON_FEATURE));
                bts = conn.read();
            } catch (IOException e) {
                try {
                    conn.close();
                } catch (Exception e1) {
                    // ignore
                }

                bioConnPool.invalidateObject(conn);
                invalided = true;
                Class<?>[] eClass = method.getExceptionTypes();

                if (eClass != null && eClass.length > 0) {
                    for (Class<?> clazz : eClass) {
                        if (e.getClass().isAssignableFrom(clazz)) {
                            throw e;
                        }
                    }
                }

                throw new RemoteSocketIOException("api=" + serviceRequestPacket.apiName + ", remoteIp="
                        + conn.getRemoteAddress() + ",(" + e.getMessage() + ")", e);
            }

            int type = AbstractServicePacket.getType(bts);
            switch (type) {
            case PacketConstant.PACKET_TYPE_ERROR:
                ErrorPacket error = new ErrorPacket();
                error.init(bts);
                packet = error;
                Exception e = venusExceptionFactory.getException(error.errorCode, error.message);
                if (e == null) {
                    throw new DefaultVenusException(error.errorCode, error.message);
                } else {
                    if (error.additionalData != null) {
                        Map<String, Type> tmap = Utils.getBeanFieldType(e.getClass(), Exception.class);
                        if (tmap != null && tmap.size() > 0) {
                            Object obj = serializer.decode(error.additionalData, tmap);
                            BeanUtils.copyProperties(e, obj);
                        }
                    }
                    throw e;
                }
            case PacketConstant.PACKET_TYPE_OK:
                OKPacket ok = new OKPacket();
                ok.init(bts);
                packet = ok;
                return null;
            case PacketConstant.PACKET_TYPE_SERVICE_RESPONSE:
                ServiceResponsePacket response = new SerializeServiceResponsePacket(serializer,
                        method.getGenericReturnType());
                response.init(bts);
                packet = response;
                return response.result;
            default: {
                logger.warn("unknow response type=" + type);
                success = false;
                return null;
            }
            }
        } catch (Exception e) {
            success = false;

            if (e instanceof CodedException
                    || (errorCode = venusExceptionFactory.getErrorCode(e.getClass())) != 0
                    || e instanceof RuntimeException) {
                if (e instanceof CodedException) {
                    errorCode = ((CodedException) e).getErrorCode();
                }
                throw e;
            } else {
                RemoteException code = e.getClass().getAnnotation(RemoteException.class);
                if (code != null) {
                    errorCode = code.errorCode();
                    throw e;
                } else {
                    ExceptionCode eCode = e.getClass().getAnnotation(ExceptionCode.class);
                    if (eCode != null) {
                        errorCode = eCode.errorCode();
                        throw e;
                    } else {
                        errorCode = -1;
                        if (conn == null) {
                            throw new DefaultVenusException(e.getMessage(), e);
                        } else {
                            throw new DefaultVenusException(
                                    e.getMessage() + ". remoteAddress=" + conn.getRemoteAddress(), e);
                        }
                    }
                }
            }
        } finally {
            if (service.athenaFlag()) {
                AthenaTransactionDelegate.getDelegate().completeClientTransaction();
            }
            long end = TimeUtil.currentTimeMillis();
            long time = end - borrowed;
            StringBuffer buffer = new StringBuffer();
            buffer.append("[").append(borrowed - start).append(",").append(time)
                    .append("]ms (*client,sync*) traceID=").append(UUID.toString(traceID)).append(", api=")
                    .append(serviceRequestPacket.apiName);
            if (remoteAddress != null) {
                buffer.append(", remote=").append(remoteAddress);
            } else {
                buffer.append(", pool=").append(bioConnPool.toString());
            }
            buffer.append(", clientID=").append(PacketConstant.VENUS_CLIENT_ID).append(", requestID=")
                    .append(serviceRequestPacket.clientRequestId);

            if (packet != null) {
                if (packet instanceof ErrorPacket) {
                    buffer.append(", errorCode=").append(((ErrorPacket) packet).errorCode);
                    buffer.append(", message=").append(((ErrorPacket) packet).message);
                } else {
                    buffer.append(", errorCode=0");
                }
            }

            if (pLevel != null) {

                if (pLevel.printParams()) {
                    buffer.append(", params=");
                    buffer.append(JSON.toJSONString(serviceRequestPacket.parameterMap, JSON_FEATURE));
                }

                if (time > pLevel.error() && pLevel.error() > 0) {
                    if (performanceLogger.isErrorEnabled()) {
                        performanceLogger.error(buffer.toString());
                    }
                } else if (time > pLevel.warn() && pLevel.warn() > 0) {
                    if (performanceLogger.isWarnEnabled()) {
                        performanceLogger.warn(buffer.toString());
                    }
                } else if (time > pLevel.info() && pLevel.info() > 0) {
                    if (performanceLogger.isInfoEnabled()) {
                        performanceLogger.info(buffer.toString());
                    }
                } else {
                    if (performanceLogger.isDebugEnabled()) {
                        performanceLogger.debug(buffer.toString());
                    }
                }
            } else {
                buffer.append(", params=");
                buffer.append(JSON.toJSONString(serviceRequestPacket.parameterMap, JSON_FEATURE));

                if (time >= 30 * 1000) {
                    if (performanceLogger.isErrorEnabled()) {
                        performanceLogger.error(buffer.toString());
                    }
                } else if (time >= 10 * 1000) {
                    if (performanceLogger.isWarnEnabled()) {
                        performanceLogger.warn(buffer.toString());
                    }
                } else if (time >= 5 * 1000) {
                    if (performanceLogger.isInfoEnabled()) {
                        performanceLogger.info(buffer.toString());
                    }
                } else {
                    if (performanceLogger.isDebugEnabled()) {
                        performanceLogger.debug(buffer.toString());
                    }
                }
            }

            if (conn != null && !invalided) {
                if (!conn.isClosed() && soTimeout > 0) {
                    conn.setSoTimeout(oldTimeout);
                }
                bioConnPool.returnObject(conn);
            }

        }
    }
}

From source file:org.evosuite.testcase.ImportsTestCodeVisitor.java

private String getTypeName(ParameterizedType type) {
    String name = getClassName((Class<?>) type.getRawType());
    Type[] types = type.getActualTypeArguments();
    boolean isDefined = false;
    for (Type parameterType : types) {
        if (parameterType instanceof Class<?> || parameterType instanceof ParameterizedType
                || parameterType instanceof WildcardType || parameterType instanceof GenericArrayType) {
            isDefined = true;/* w  w  w.  ja  va2 s.  c  om*/
            break;
        }
    }
    if (isDefined) {
        if (types.length > 0) {
            name += "<";
            for (int i = 0; i < types.length; i++) {
                if (i != 0)
                    name += ", ";

                name += getTypeName(types[i]);
            }
            name += ">";
        }
    }
    return name;
}

From source file:com.thinkbiganalytics.spark.datavalidator.Validator.java

protected Class resolveValidatorParamType(ValidationPolicy validator) {
    Class expectedParamClazz = validatorParamType.get(validator.getClass());
    if (expectedParamClazz == null) {
        // Cache for future references

        Object t = validator.getClass().getGenericInterfaces()[0];
        if (t instanceof ParameterizedType) {
            ParameterizedType type = (ParameterizedType) t;
            expectedParamClazz = (Class) type.getActualTypeArguments()[0];
        } else {//www.  ja  v a  2  s  .  c o m
            expectedParamClazz = String.class;
        }
        validatorParamType.put(validator.getClass(), expectedParamClazz);
    }
    return expectedParamClazz;
}

From source file:org.apache.axis2.jaxws.description.impl.ParameterDescriptionImpl.java

/**
 * TEMPORARY METHOD!  For a JAX-WS Holder<T> this returns the class associated with <T>. For a
 * Holder<Generic<...>>, it returns the class associated with Generic.  If the type is not a
 * JAX-WS Holder, return a null./*from   w w  w.  j  a  v  a2s  .  c  o m*/
 * <p/>
 * This method SHOULD BE REMOVED when the description layer is refactored to use only DBC and
 * not Java reflection directly.
 *
 * @param parameterGenericType
 * @return
 */
// TODO: Remove this method when code refactored to only use DBC.
private Class getGenericParameterActualType(ParameterizedType parameterGenericType) {
    Class returnClass = null;
    // If this is a JAX-WS Holder type, then get the actual type.  Note that we can't use the
    // isHolderType method yet because the class variable it is going to check (parameterHolderActualType)
    // hasn't been initialized yet.
    if (parameterGenericType != null && parameterGenericType.getRawType() == javax.xml.ws.Holder.class) {
        // NOTE
        // If you change this code, please remember to change 
        // OperationDesc.getResultActualType

        Type type = parameterGenericType.getActualTypeArguments()[0];
        if (type != null && ParameterizedType.class.isInstance(type)) {
            // For types of Holder<Generic<K,V>>, return class associated with Generic
            returnClass = (Class) ((ParameterizedType) type).getRawType();
        } else if (type != null && GenericArrayType.class.isInstance(type)) {
            Type componentType = ((GenericArrayType) type).getGenericComponentType();
            Class arrayClass = null;
            if (ParameterizedType.class.isInstance(componentType)) {
                // For types of Holder<Generic<K,V>[]>, return class associated with Generic[]
                arrayClass = (Class) ((ParameterizedType) componentType).getRawType();
            } else {
                // For types of Holder<Object[]>, return class associated with Object[]
                arrayClass = (Class) componentType;
            }
            // REVIEW: This only works for a single dimension array!  Note that if this method is removed
            //         when DBC is used, just make sure DBC supports multi-dim arrays
            returnClass = Array.newInstance(arrayClass, 0).getClass();
        } else {
            // For types of Holder<Object>, return the class associated with Object
            returnClass = (Class) type;
        }
    }

    return returnClass;
}