Example usage for java.lang.reflect Type getClass

List of usage examples for java.lang.reflect Type getClass

Introduction

In this page you can find the example usage for java.lang.reflect Type getClass.

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:io.servicecomb.swagger.invocation.converter.ConverterMgr.java

protected Converter findCollectionToArray(Type src, Type target) {
    if (ParameterizedType.class.isAssignableFrom(src.getClass()) && target.getClass().equals(Class.class)) {
        ParameterizedType srcType = (ParameterizedType) src;
        Class<?> srcCls = (Class<?>) srcType.getRawType();
        Class<?> targetCls = (Class<?>) target;

        if (Collection.class.isAssignableFrom(srcCls) && targetCls.isArray()
                && srcType.getActualTypeArguments()[0].equals(targetCls.getComponentType())) {
            Converter converter = collectionToArrayMap.get(target);
            if (converter == null) {
                converter = new SameElementCollectionToArray(targetCls.getComponentType());
                collectionToArrayMap.put(target, converter);
            }/*from   w ww. ja  v a2s  .c o m*/
            return converter;
        }
    }

    return null;
}

From source file:com.github.luluvise.droid_utils.json.jackson.JacksonObjectParser.java

public Object parseAndClose(InputStream in, Charset charset, Type dataType) throws IOException {
    // encoding is automatically detected by ObjectMapper
    // TODO detect if passed class is consistent
    return mMapper.readValue(in, dataType.getClass());
}

From source file:org.ocelotds.core.services.ArgumentConvertor.java

private JavaType getJavaType(Type type) {
    Class clazz;//from  ww  w. ja v  a  2  s  .  c o m
    logger.debug("Computing type of {} - {}", type.getClass(), type.toString());
    if (type instanceof ParameterizedType) {
        clazz = (Class) ((ParameterizedType) type).getRawType();
    } else {
        clazz = (Class) type;
    }
    JavaType javaType;
    Type actualType;
    if (Collection.class.isAssignableFrom(clazz)) {
        ParameterizedType pt = (ParameterizedType) type;
        actualType = pt.getActualTypeArguments()[0];
        JavaType t1 = getJavaType(actualType);
        javaType = CollectionType.construct(Collection.class, t1);
    } else if (clazz.isArray()) {
        Class t = clazz.getComponentType();
        JavaType t1 = getJavaType(t);
        javaType = ArrayType.construct(t1, null, null);
    } else if (Map.class.isAssignableFrom(clazz)) {
        ParameterizedType pt = (ParameterizedType) type;
        actualType = pt.getActualTypeArguments()[0];
        JavaType t1 = getJavaType(actualType);
        actualType = pt.getActualTypeArguments()[1];
        JavaType t2 = getJavaType(actualType);
        javaType = MapType.construct(Map.class, t1, t2);
    } else {
        javaType = SimpleType.construct(clazz);
    }
    return javaType;
}

From source file:org.openflexo.antar.binding.TypeUtils.java

public static Class getBaseClass(Type aType) {
    if (aType == null) {
        return null;
    }// ww w . j av a  2 s .  co m
    if (aType instanceof CustomType) {
        return ((CustomType) aType).getBaseClass();
    }
    if (isResolved(aType)) {
        if (aType instanceof Class) {
            return (Class) aType;
        } else if (aType instanceof ParameterizedType) {
            Type rawType = ((ParameterizedType) aType).getRawType();
            if (rawType instanceof Class) {
                return (Class) rawType;
            }
            logger.warning("Not handled: " + aType.getClass().getName());
            return null;
        } else {
            logger.warning("Not handled: " + aType.getClass().getName());
            return null;
        }
    }
    if (aType instanceof WildcardType) {
        // System.out.println("WildcardType: " + aType);
        Type[] upperBounds = ((WildcardType) aType).getUpperBounds();
        Type[] lowerBounds = ((WildcardType) aType).getLowerBounds();
        // System.out.println("upper=" + upperBounds + " size=" + upperBounds.length);
        // System.out.println("lower=" + upperBounds + " size=" + lowerBounds.length);
        if (upperBounds.length == 1 && lowerBounds.length == 0) {
            return getBaseClass(upperBounds[0]);
        }
    }
    if (aType instanceof TypeVariable) {
        Type[] bounds = ((TypeVariable<?>) aType).getBounds();
        if (bounds.length == 1) {
            return getBaseClass(bounds[0]);
        }
    }
    logger.warning("Not handled: " + aType.getClass().getName());
    return null;
}

From source file:org.ocelotds.core.services.ArgumentConvertor.java

/**
 * try to convert json argument in java type
 *
 * @param arg/*from w  w w  .  j  a v  a 2 s . c o m*/
 * @param paramType
 * @return
 * @throws IllegalArgumentException
 */
Object convertArgument(String arg, Type paramType) throws IllegalArgumentException {
    Object result = null;
    if (null == arg || "null".equals(arg)) {
        return result;
    }
    logger.debug("Try to convert {} : param = {} : {}", new Object[] { arg, paramType, paramType.getClass() });
    try { // GenericArrayType, ParameterizedType, TypeVariable<D>, WildcardType, Class
        if (ParameterizedType.class.isInstance(paramType)) {
            JavaType javaType = getJavaType(paramType);
            logger.debug("Try to convert '{}'to JavaType : '{}'", arg, paramType);
            result = getObjectMapper().readValue(arg, javaType);
            logger.debug("Conversion of '{}'to '{}' : OK", arg, paramType);
        } else if (Class.class.isInstance(paramType)) {
            Class cls = (Class) paramType;
            logger.debug("Try to convert '{}' to Class '{}'", arg, paramType);
            checkStringArgument(cls, arg);
            result = getObjectMapper().readValue(arg, cls);
            logger.debug("Conversion of '{}'to '{}' : OK", arg, paramType);
        } else { // GenericArrayType, TypeVariable<D>, WildcardType
            logger.warn("Conversion of '{}'to '{}' not yet supported", arg, paramType);
        }
    } catch (IOException ex) {
        logger.debug("Conversion of '{}' to '{}' failed", arg, paramType);
        throw new IllegalArgumentException(paramType.toString());
    }
    return result;
}

From source file:org.evosuite.utils.generic.GenericAccessibleObject.java

protected static Type getTypeFromExactReturnType(Type returnType, Type type) {
    if (returnType instanceof ParameterizedType && type instanceof ParameterizedType)
        return getTypeFromExactReturnType((ParameterizedType) returnType, (ParameterizedType) type);
    else if (returnType instanceof GenericArrayType && type instanceof GenericArrayType)
        return getTypeFromExactReturnType((GenericArrayType) returnType, (GenericArrayType) type);
    else if (returnType instanceof ParameterizedType && type instanceof GenericArrayType)
        return getTypeFromExactReturnType((ParameterizedType) returnType, (GenericArrayType) type);
    else if (returnType instanceof GenericArrayType && type instanceof ParameterizedType)
        return getTypeFromExactReturnType((GenericArrayType) returnType, (ParameterizedType) type);
    else if (returnType instanceof Class<?>)
        return returnType;
    else if (type instanceof Class<?>)
        return type;
    else// ww  w .  j a  va2s.c om
        throw new RuntimeException("Incompatible types: " + returnType.getClass() + " and " + type.getClass()
                + ": " + returnType + " and " + type);
}

From source file:org.fcrepo.transform.http.responses.QueryExecutionProvider.java

@Override
public boolean isWriteable(final Class<?> type, final Type genericType, final Annotation[] annotations,
        final MediaType mediaType) {

    // we can return a result for any MIME type that Jena can serialize
    final Boolean appropriateResultType = getResultsFormat(mediaType) != FMT_UNKNOWN;
    return appropriateResultType && (QueryExecution.class.isAssignableFrom(type)
            || QueryExecution.class.isAssignableFrom(genericType.getClass()));
}

From source file:nl.luminis.test.util.annotations.HierarchyDiscovery.java

private Type resolveParameterizedType(ParameterizedType beanType, ParameterizedType parameterizedType) {
    Type rawType = parameterizedType.getRawType();
    Type[] actualTypes = parameterizedType.getActualTypeArguments();

    Type resolvedRawType = resolveType(beanType, beanType, rawType);
    Type[] resolvedActualTypes = new Type[actualTypes.length];

    for (int i = 0; i < actualTypes.length; i++) {
        resolvedActualTypes[i] = resolveType(beanType, beanType, actualTypes[i]);
    }/* w  ww.j  av  a 2s  .c om*/
    // reconstruct ParameterizedType by types resolved TypeVariable.
    return TypeUtils.parameterizeWithOwner(parameterizedType.getOwnerType(), resolvedRawType.getClass(),
            resolvedActualTypes);
}

From source file:org.openmrs.module.sync.SyncUtil.java

/**
 * This monstrosity looks for getter(s) on the parent object of an OpenmrsObject that return a
 * collection of the originally passed in OpenmrsObject type. This then explicitly removes the
 * object from the parent collection, and if the parent is a Patient or Person, calls save on
 * the parent./*from   w  w w  .  j ava  2s .  com*/
 * 
 * @param item -- the OpenmrsObject to remove and save
 */
private static void removeFromPatientParentCollectionAndSave(OpenmrsObject item) {
    Field[] f = item.getClass().getDeclaredFields();
    for (int k = 0; k < f.length; k++) {
        Type fieldType = f[k].getGenericType();
        if (org.openmrs.OpenmrsObject.class.isAssignableFrom((Class) fieldType)) { //if the property is an OpenmrsObject (excludes lists, etc..)
            Method getter = getGetterMethod(item.getClass(), f[k].getName()); //get the getters
            OpenmrsObject parent = null; //the parent object
            if (getter == null) {
                continue; //no prob -- eliminates most utility methods on item
            }
            try {
                parent = (OpenmrsObject) getter.invoke(item, null); //get the parent object
            } catch (Exception ex) {
                log.debug(
                        "in removeFromParentCollection:  getter probably did not return an object that could be case as an OpenmrsObject",
                        ex);
            }
            if (parent != null) {
                Method[] methods = getter.getReturnType().getDeclaredMethods(); //get the Parent's methods to inspect
                for (Method method : methods) {
                    Type type = method.getGenericReturnType();
                    //return is a parameterizable and there are 0 arguments to method and the return is a Collection
                    if (ParameterizedType.class.isAssignableFrom(type.getClass())
                            && method.getGenericParameterTypes().length == 0
                            && method.getName().contains("get")) { //get the methods on Person that return Lists or Sets
                        ParameterizedType pt = (ParameterizedType) type;
                        for (int i = 0; i < pt.getActualTypeArguments().length; i++) {
                            Type t = pt.getActualTypeArguments()[i];
                            // if the return type matches the original object, and the return is not a Map
                            if (item.getClass().equals(t)
                                    && !pt.getRawType().toString().equals(java.util.Map.class.toString())
                                    && java.util.Collection.class.isAssignableFrom((Class) pt.getRawType())) {
                                try {
                                    Object colObj = (Object) method.invoke(parent, null); //get the list
                                    if (colObj != null) {
                                        java.util.Collection collection = (java.util.Collection) colObj;
                                        Iterator it = collection.iterator();
                                        boolean atLeastOneRemoved = false;
                                        while (it.hasNext()) {
                                            OpenmrsObject omrsobj = (OpenmrsObject) it.next();
                                            if (omrsobj.getUuid() != null
                                                    && omrsobj.getUuid().equals(item.getUuid())) { //compare uuid of original item with Collection contents
                                                it.remove();
                                                atLeastOneRemoved = true;
                                            }
                                            if (atLeastOneRemoved && (parent instanceof org.openmrs.Patient
                                                    || parent instanceof org.openmrs.Person)) {
                                                // this is commented out because deleting of patients fails if it is here.
                                                // we really should not need to call "save", that can only cause problems.
                                                // removing the object from the parent collection is the important part, which we're doing above
                                                //Context.getService(SyncService.class).saveOrUpdate(parent);
                                            }
                                        }
                                    }
                                } catch (Exception ex) {
                                    log.error("Failed to build new collection", ex);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

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   ww w.  ja va 2  s  . c om
    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));
}