Example usage for java.lang.reflect ParameterizedType getRawType

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

Introduction

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

Prototype

Type getRawType();

Source Link

Document

Returns the Type object representing the class or interface that declared this type.

Usage

From source file:org.protorabbit.json.DefaultSerializer.java

@SuppressWarnings("unchecked")
void invokeMethod(Method[] methods, String key, String name, JSONObject jo, Object targetObject) {
    Object param = null;/*  w  w w .  j  a  v a 2  s.  com*/
    Throwable ex = null;
    for (int i = 0; i < methods.length; i++) {
        Method m = methods[i];
        if (m.getName().equals(name)) {
            Class<?>[] paramTypes = m.getParameterTypes();
            if (paramTypes.length == 1 && jo.has(key)) {
                Class<?> tparam = paramTypes[0];
                boolean allowNull = false;
                try {
                    if (jo.isNull(key)) {
                        // do nothing because param is already null : lets us not null on other types
                    } else if (Long.class.isAssignableFrom(tparam) || tparam == long.class) {
                        param = new Long(jo.getLong(key));
                    } else if (Double.class.isAssignableFrom(tparam) || tparam == double.class) {
                        param = new Double(jo.getDouble(key));
                    } else if (Integer.class.isAssignableFrom(tparam) || tparam == int.class) {
                        param = new Integer(jo.getInt(key));
                    } else if (String.class.isAssignableFrom(tparam)) {
                        param = jo.getString(key);
                    } else if (Enum.class.isAssignableFrom(tparam)) {
                        param = Enum.valueOf((Class<? extends Enum>) tparam, jo.getString(key));
                    } else if (Boolean.class.isAssignableFrom(tparam)) {
                        param = new Boolean(jo.getBoolean(key));
                    } else if (jo.isNull(key)) {
                        param = null;
                        allowNull = true;
                    } else if (Collection.class.isAssignableFrom(tparam)) {

                        if (m.getGenericParameterTypes().length > 0) {
                            Type t = m.getGenericParameterTypes()[0];
                            if (t instanceof ParameterizedType) {
                                ParameterizedType tv = (ParameterizedType) t;
                                if (tv.getActualTypeArguments().length > 0
                                        && tv.getActualTypeArguments()[0] == String.class) {

                                    List<String> ls = new ArrayList<String>();
                                    JSONArray ja = jo.optJSONArray(key);
                                    if (ja != null) {
                                        for (int j = 0; j < ja.length(); j++) {
                                            ls.add(ja.getString(j));
                                        }
                                    }
                                    param = ls;
                                } else if (tv.getActualTypeArguments().length == 1) {
                                    ParameterizedType type = (ParameterizedType) tv.getActualTypeArguments()[0];
                                    Class itemClass = (Class) type.getRawType();
                                    if (itemClass == Map.class && type.getActualTypeArguments().length == 2
                                            && type.getActualTypeArguments()[0] == String.class
                                            && type.getActualTypeArguments()[1] == Object.class) {

                                        List<Map<String, Object>> ls = new ArrayList<Map<String, Object>>();

                                        JSONArray ja = jo.optJSONArray(key);
                                        if (ja != null) {
                                            for (int j = 0; j < ja.length(); j++) {
                                                Map<String, Object> map = new HashMap<String, Object>();
                                                JSONObject mo = ja.getJSONObject(j);
                                                Iterator<String> keys = mo.keys();
                                                while (keys.hasNext()) {
                                                    String okey = keys.next();
                                                    Object ovalue = null;
                                                    // make sure we don't get JSONObject$Null
                                                    if (!mo.isNull(okey)) {
                                                        ovalue = mo.get(okey);
                                                    }
                                                    map.put(okey, ovalue);
                                                }
                                                ls.add(map);
                                            }
                                        }
                                        param = ls;
                                    } else {
                                        getLogger().warning(
                                                "Don't know how to handle Collection of type : " + itemClass);
                                    }

                                } else {
                                    getLogger().warning("Don't know how to handle Collection of type : "
                                            + tv.getActualTypeArguments()[0]);
                                }
                            }
                        }
                    } else {
                        getLogger().warning(
                                "Unable to serialize " + key + " :  Don't know how to handle " + tparam);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                if (param != null || allowNull) {

                    try {

                        if (m != null) {
                            Object[] args = { param };
                            m.invoke(targetObject, args);
                            ex = null;
                            break;
                        }
                    } catch (SecurityException e) {
                        ex = e;
                    } catch (IllegalArgumentException e) {
                        ex = e;
                    } catch (IllegalAccessException e) {
                        ex = e;
                    } catch (InvocationTargetException e) {
                        ex = e;
                    }
                }
            }
        }
    }
    if (ex != null) {
        if (ex instanceof RuntimeException) {
            throw (RuntimeException) ex;
        } else {
            throw new RuntimeException(ex);
        }
    }
}

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

/**
 * Checks that the actual field is parameterized.
 * //  ww w  .  j a va2s  . co  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:org.springframework.data.document.mongodb.SimpleMongoConverter.java

List<Class<?>> getGenericParameters(Type genericParameterType) {

    List<Class<?>> actualGenericParameterTypes = new ArrayList<Class<?>>();

    if (genericParameterType instanceof ParameterizedType) {
        ParameterizedType aType = (ParameterizedType) genericParameterType;
        Type[] parameterArgTypes = aType.getActualTypeArguments();
        for (Type parameterArgType : parameterArgTypes) {
            if (parameterArgType instanceof GenericArrayType) {
                Class<?> arrayType = (Class<?>) ((GenericArrayType) parameterArgType).getGenericComponentType();
                actualGenericParameterTypes.add(Array.newInstance(arrayType, 0).getClass());
            } else {
                if (parameterArgType instanceof ParameterizedType) {
                    ParameterizedType paramTypeArgs = (ParameterizedType) parameterArgType;
                    actualGenericParameterTypes.add((Class<?>) paramTypeArgs.getRawType());
                } else {
                    if (parameterArgType instanceof TypeVariable) {
                        throw new RuntimeException(
                                "Can not map " + ((TypeVariable<?>) parameterArgType).getName());
                    } else {
                        if (parameterArgType instanceof Class) {
                            actualGenericParameterTypes.add((Class<?>) parameterArgType);
                        } else {
                            throw new RuntimeException("Can not map " + parameterArgType);
                        }//from   w w  w .  j  a  va  2s  . c om
                    }
                }
            }
        }
    }

    return actualGenericParameterTypes;
}

From source file:org.eclipse.wb.internal.core.utils.reflect.ReflectionUtils.java

/**
 * @param runtime/*from  ww  w. j av a 2 s.  c om*/
 *          is <code>true</code> if we need name for class loading, <code>false</code> if we need
 *          name for source generation.
 * 
 * @return the fully qualified name of given {@link Type}.
 */
public static String getFullyQualifiedName(Type type, boolean runtime) {
    Assert.isNotNull(type);
    // Class
    if (type instanceof Class<?>) {
        Class<?> clazz = (Class<?>) type;
        // array
        if (clazz.isArray()) {
            return getFullyQualifiedName(clazz.getComponentType(), runtime) + "[]";
        }
        // object
        String name = clazz.getName();
        if (!runtime) {
            name = name.replace('$', '.');
        }
        return name;
    }
    // GenericArrayType
    if (type instanceof GenericArrayType) {
        GenericArrayType genericArrayType = (GenericArrayType) type;
        return getFullyQualifiedName(genericArrayType.getGenericComponentType(), runtime) + "[]";
    }
    // ParameterizedType
    if (type instanceof ParameterizedType) {
        ParameterizedType parameterizedType = (ParameterizedType) type;
        Type rawType = parameterizedType.getRawType();
        // raw type
        StringBuilder sb = new StringBuilder();
        sb.append(getFullyQualifiedName(rawType, runtime));
        // type arguments
        sb.append("<");
        boolean firstTypeArgument = true;
        for (Type typeArgument : parameterizedType.getActualTypeArguments()) {
            if (!firstTypeArgument) {
                sb.append(",");
            }
            firstTypeArgument = false;
            sb.append(getFullyQualifiedName(typeArgument, runtime));
        }
        sb.append(">");
        // done
        return sb.toString();
    }
    // WildcardType
    if (type instanceof WildcardType) {
        WildcardType wildcardType = (WildcardType) type;
        return "? extends " + getFullyQualifiedName(wildcardType.getUpperBounds()[0], runtime);
    }
    // TypeVariable
    TypeVariable<?> typeVariable = (TypeVariable<?>) type;
    return typeVariable.getName();
}

From source file:org.springframework.data.document.mongodb.convert.SimpleMongoConverter.java

public List<Class<?>> getGenericParameters(Type genericParameterType) {

    List<Class<?>> actualGenericParameterTypes = new ArrayList<Class<?>>();

    if (genericParameterType instanceof ParameterizedType) {
        ParameterizedType aType = (ParameterizedType) genericParameterType;
        Type[] parameterArgTypes = aType.getActualTypeArguments();
        for (Type parameterArgType : parameterArgTypes) {
            if (parameterArgType instanceof GenericArrayType) {
                Class<?> arrayType = (Class<?>) ((GenericArrayType) parameterArgType).getGenericComponentType();
                actualGenericParameterTypes.add(Array.newInstance(arrayType, 0).getClass());
            } else {
                if (parameterArgType instanceof ParameterizedType) {
                    ParameterizedType paramTypeArgs = (ParameterizedType) parameterArgType;
                    actualGenericParameterTypes.add((Class<?>) paramTypeArgs.getRawType());
                } else {
                    if (parameterArgType instanceof TypeVariable) {
                        throw new RuntimeException(
                                "Can not map " + ((TypeVariable<?>) parameterArgType).getName());
                    } else {
                        if (parameterArgType instanceof Class) {
                            actualGenericParameterTypes.add((Class<?>) parameterArgType);
                        } else {
                            throw new RuntimeException("Can not map " + parameterArgType);
                        }/* w  w  w .j  a va 2s .c  o  m*/
                    }
                }
            }
        }
    }

    return actualGenericParameterTypes;
}

From source file:org.powertac.logtool.common.DomainObjectReader.java

private Object resolveArg(Type type, String arg) throws MissingDomainObject {
    // type can be null in a few cases - nothing to be done about it?
    if (null == type) {
        return null;
    }/*from ww  w.  j  a v  a 2  s.  c o m*/

    // check for non-parameterized types
    if (type instanceof Class) {
        Class<?> clazz = (Class<?>) type;
        if (clazz.isEnum()) {
            return Enum.valueOf((Class<Enum>) type, arg);
        } else {
            return resolveSimpleArg(clazz, arg);
        }
    }

    // check for collection, denoted by leading (
    if (type instanceof ParameterizedType) {
        ParameterizedType ptype = (ParameterizedType) type;
        Class<?> clazz = (Class<?>) ptype.getRawType();
        boolean isCollection = false;
        if (clazz.equals(Collection.class))
            isCollection = true;
        else {
            Class<?>[] ifs = clazz.getInterfaces();
            for (Class<?> ifc : ifs) {
                if (ifc.equals(Collection.class)) {
                    isCollection = true;
                    break;
                }
            }
        }
        if (isCollection) {
            // expect arg to start with "("
            log.debug("processing collection " + clazz.getName());
            if (arg.charAt(0) != '(') {
                log.error("Collection arg " + arg + " does not start with paren");
                return null;
            }
            // extract element type and resolve recursively
            Type[] tas = ptype.getActualTypeArguments();
            if (1 == tas.length) {
                Class<?> argClazz = (Class<?>) tas[0];
                // create an instance of the collection
                Collection<Object> coll;
                // resolve interfaces into actual classes
                if (clazz.isInterface())
                    clazz = ifImplementors.get(clazz);
                try {
                    coll = (Collection<Object>) clazz.newInstance();
                } catch (Exception e) {
                    log.error("Exception creating collection: " + e.toString());
                    return null;
                }
                // at this point, we can split the string and resolve recursively
                String body = arg.substring(1, arg.indexOf(')'));
                String[] items = body.split(",");
                for (String item : items) {
                    coll.add(resolveSimpleArg(argClazz, item));
                }
                return coll;
            }
        }
    }

    // if we get here, no resolution
    log.error("unresolved arg: type = " + type + ", arg = " + arg);
    return null;
}

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);
            }/*  ww w .  j a v a  2 s  .  c  o  m*/
        }
    }
}

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./* w w w.  jav a  2 s  . c  om*/
 * <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;
}

From source file:org.projectforge.continuousdb.TableAttribute.java

/**
 * @param method/* www  .j av  a 2  s.  co  m*/
 * @return
 */
private void setGenericReturnType(final Method method) {

    Type returnType = method.getGenericReturnType();
    if ((returnType instanceof ParameterizedType) == false) {
        return;
    }
    final ParameterizedType type = (ParameterizedType) returnType;
    OneToMany oneToMany = method.getAnnotation(OneToMany.class);
    if (oneToMany != null && oneToMany.targetEntity() != null && oneToMany.targetEntity() != Void.TYPE) {
        if (type.getRawType() instanceof Class) {
            if (List.class.isAssignableFrom((Class) type.getRawType()) == true) {
                genericType = oneToMany.targetEntity();
                return;
            }
        }
    }
    final Type[] typeArguments = type.getActualTypeArguments();
    if (typeArguments.length == 0) {
        return;
    }
    if (typeArguments[0] instanceof ParameterizedType) {
        final ParameterizedType nt = (ParameterizedType) typeArguments[0];
        final Type[] nst = nt.getActualTypeArguments();
        if (nst.length > 0) {
            final Class<?> typeArgClass = (Class<?>) nst[0];
            if (log.isDebugEnabled() == true) {
                log.debug("Generic type found for '" + entityClass + "." + property + "': '" + typeArgClass
                        + "'.");
            }
            genericType = typeArgClass;
        }
    }
    if ((typeArguments[0] instanceof Class) == false) {
        // opps
        final Class<?> thclas = typeArguments[0].getClass();
        log.error("Cannot determine entity type: " + thclas.getName() + " in method: " + method);
    } else {
        final Class<?> typeArgClass = (Class<?>) typeArguments[0];
        if (log.isDebugEnabled() == true) {
            log.debug("Generic type found for '" + entityClass + "." + property + "': '" + typeArgClass + "'.");
        }
        genericType = typeArgClass;
    }

}

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.// ww  w .  j  a  v  a 2s.  c o m
 * 
 * @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);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}