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.nextframework.controller.ExtendedBeanWrapper.java

protected Object getPropertyValue(PropertyTokenHolder tokens) throws BeansException {
    String propertyName = tokens.canonicalName;
    String actualName = tokens.actualName;
    PropertyDescriptor pd = getPropertyDescriptorInternal(tokens.actualName);
    if (pd == null || pd.getReadMethod() == null) {
        throw new NotReadablePropertyException(getRootClass(), this.nestedPath + propertyName);
    }//from ww  w .  j a  va 2 s.c  om
    if (logger.isDebugEnabled())
        logger.debug("About to invoke read method [" + pd.getReadMethod() + "] on object of class ["
                + this.object.getClass().getName() + "]");
    try {
        Object value = pd.getReadMethod().invoke(this.object, (Object[]) null);
        Type genericReturnType = pd.getReadMethod().getGenericReturnType();
        Class rawReturnType = pd.getReadMethod().getReturnType();
        if (tokens.keys != null) {
            // apply indexes and map keys
            for (int i = 0; i < tokens.keys.length; i++) {
                String key = tokens.keys[i];

                //cria listas sob demanda.. no  mais necessrio utilizar o ListSet no pojo
                Class originalClass = null;
                if (value != null) {
                    originalClass = value.getClass();
                }
                if (value == null && rawReturnType != null && genericReturnType instanceof ParameterizedType) {
                    ParameterizedType parameterizedType = (ParameterizedType) genericReturnType;
                    if (Map.class.isAssignableFrom(rawReturnType)) {
                        value = new LinkedHashMap();
                        pd.getWriteMethod().invoke(this.object, value);
                    } else if (List.class.isAssignableFrom(rawReturnType)
                            || Set.class.isAssignableFrom(rawReturnType)) {
                        Type type = parameterizedType.getActualTypeArguments()[0];
                        value = new ListSet(type instanceof Class ? (Class) type
                                : (Class) ((ParameterizedType) type).getRawType());
                        pd.getWriteMethod().invoke(this.object, value);
                    }
                }
                //fim da criacao sob demanda

                if (value == null) {
                    throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName,
                            "Cannot access indexed value of property referenced in indexed " + "property path '"
                                    + propertyName + "': returned null");
                } else if (value.getClass().isArray()) {
                    value = Array.get(value, Integer.parseInt(key));
                } else if (value instanceof List) {
                    List list = (List) value;
                    try {
                        value = list.get(Integer.parseInt(key));
                    } catch (IndexOutOfBoundsException e) {
                        //tentar instanciar um bean da lista
                        String extraMessage = "";
                        if (genericReturnType instanceof ParameterizedType) {
                            ParameterizedType parameterizedType = (ParameterizedType) genericReturnType;
                            Type type = parameterizedType.getActualTypeArguments()[0];
                            if (type instanceof Class) {
                                Class clazz = (Class) type;
                                extraMessage = "A classe " + clazz.getName()
                                        + " no possui um construtor publico sem argumentos";
                                try {
                                    value = clazz.newInstance();
                                    int index = Integer.parseInt(key);
                                    int insertNulls = index - list.size();
                                    while (insertNulls > 0) { // 11/06/2012
                                        list.add(null);
                                        insertNulls--;
                                    }

                                    list.add(index, value); // CDIGO 15/01/2007
                                } catch (InstantiationException e1) {
                                    throw new RuntimeException(
                                            "Aconteceu um erro ao acessar um elemento da classe "
                                                    + originalClass.getName() + " propriedade " + propertyName
                                                    + "  No foi possvel instanciar um bean para preencher a lista. "
                                                    + extraMessage,
                                            e);
                                }
                            }
                        } else if (originalClass != null) {
                            throw new RuntimeException("Aconteceu um erro ao acessar um elemento da classe "
                                    + originalClass.getName() + " propriedade " + propertyName
                                    + "  Sugesto: Utilize uma lista que cresa quando for necessrio como o ListSet ou no instancie nenhum objeto para essa propriedade",
                                    e);
                        } else {
                            throw e;
                        }
                    }
                } else if (value instanceof Set) {
                    // apply index to Iterator in case of a Set
                    //TODO CRIAR AUTOMATICAMENTE O BEAN DO SET
                    Set set = (Set) value;
                    int index = Integer.parseInt(key);
                    if (index < 0 || index >= set.size()) {
                        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                                "Cannot get element with index " + index + " from Set of size " + set.size()
                                        + ", accessed using property path '" + propertyName + "'"
                                        + "  Sugesto: Utilize o ListSet ou no instancie nenhum objeto");
                    }
                    Iterator it = set.iterator();
                    for (int j = 0; it.hasNext(); j++) {
                        Object elem = it.next();
                        if (j == index) {
                            value = elem;
                            break;
                        }
                    }
                } else if (value instanceof Map) {
                    if (!(genericReturnType instanceof ParameterizedType)) {
                        throw new NotParameterizedTypeException(
                                "Path direciona a um Map no parameterizado com generics. " + " Propriedade '"
                                        + this.nestedPath + propertyName + "' da classe ["
                                        + this.rootObject.getClass().getName() + "]");
                    }
                    ParameterizedType parameterizedType = ((ParameterizedType) genericReturnType);
                    Type mapKeyType = parameterizedType.getActualTypeArguments()[0];
                    Type mapValueType = parameterizedType.getActualTypeArguments()[1];
                    Class rawKeyType = mapKeyType instanceof Class ? (Class) mapKeyType
                            : (Class) ((ParameterizedType) mapKeyType).getRawType();
                    Class rawValueType = mapValueType instanceof Class ? (Class) mapValueType
                            : (Class) ((ParameterizedType) mapValueType).getRawType();
                    Object objectKey = doTypeConversionIfNecessary(key, rawKeyType);
                    Map map = (Map) value;
                    value = map.get(objectKey);
                    if (value == null && List.class.isAssignableFrom(rawValueType)) {
                        List mapValue;
                        try {
                            Type listType = ((ParameterizedType) mapValueType).getActualTypeArguments()[0];
                            mapValue = new ListSet(listType instanceof Class ? (Class) listType
                                    : (Class) ((ParameterizedType) listType).getRawType());
                        } catch (ClassCastException e) {
                            throw new RuntimeException(
                                    "Na path " + propertyName + " um mapa contm uma lista no parametrizada");
                        }
                        map.put(objectKey, mapValue);
                        value = mapValue;
                    }
                } else {
                    throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                            "Property referenced in indexed property path '" + propertyName
                                    + "' is neither an array nor a List nor a Set nor a Map; returned value was ["
                                    + value + "]");
                }
            }
        }
        return value;
    } catch (InvocationTargetException ex) {
        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                "Getter for property '" + actualName + "' threw exception", ex);
    } catch (IllegalAccessException ex) {
        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                "Illegal attempt to get property '" + actualName + "' threw exception", ex);
    } catch (IndexOutOfBoundsException ex) {
        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                "Index of out of bounds in property path '" + propertyName + "'", ex);
    } catch (NumberFormatException ex) {
        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                "Invalid index in property path '" + propertyName + "'", ex);
    }
}

From source file:co.paralleluniverse.galaxy.core.Cache.java

private static boolean isVoidLineFunction(Class<?> clazz) {
    if (clazz == null)
        return false;
    for (java.lang.reflect.Type iface : clazz.getGenericInterfaces()) {
        if (iface instanceof java.lang.reflect.ParameterizedType) {
            java.lang.reflect.ParameterizedType pt = (java.lang.reflect.ParameterizedType) iface;
            if (pt.getRawType() == LineFunction.class)
                return (pt.getActualTypeArguments()[0] == Void.class);
            boolean r = isVoidLineFunction((Class) pt.getRawType());
            if (r)
                return true;
        } else if (iface == LineFunction.class)
            return false;

        boolean r = isVoidLineFunction((Class) iface);
        if (r)/*from  w w  w.  j  a  v  a2 s. com*/
            return true;
    }
    return isVoidLineFunction(clazz.getSuperclass());
}

From source file:fr.certu.chouette.command.Command.java

/**
 * @param objectType//from  w w  w . j  av  a2 s  .com
 * @param field
 * @param indent
 * @throws Exception
 */
private void printField(Class<?> objectType, Field field, String indent) throws Exception {
    String fieldName = field.getName().toLowerCase();
    if (fieldName.equals("importeditems"))
        return;
    if (fieldName.endsWith("id") || fieldName.endsWith("ids")) {
        if (!fieldName.equals("objectid") && !fieldName.equals("creatorid")
                && !fieldName.equals("areacentroid"))
            return;
    }
    if (findAccessor(objectType, field.getName(), "get", false) == null
            && findAccessor(objectType, field.getName(), "is", false) == null) {
        return;
    }
    Class<?> type = field.getType();

    if (type.isPrimitive()) {
        System.out.print(indent + "- " + field.getName());
        System.out.print(" : type " + type.getName());
        if (findAccessor(objectType, field.getName(), "set", false) == null) {
            System.out.print(" (readonly)");
        }
    } else {
        if (type.getSimpleName().equals("List")) {
            String name = field.getName();
            name = name.substring(0, name.length() - 1);
            ParameterizedType ptype = (ParameterizedType) field.getGenericType();
            Class<?> itemType = (Class<?>) ptype.getActualTypeArguments()[0];
            System.out.print(indent + "- " + name);
            System.out.print(" : collection of type " + itemType.getSimpleName());
            if (findAccessor(objectType, name, "add", false) != null) {
                System.out.print(" (add allowed)");
            }
            if (findAccessor(objectType, name, "remove", false) != null) {
                System.out.print(" (remove allowed)");
            }
            type = itemType;
        } else {
            System.out.print(indent + "- " + field.getName());
            System.out.print(" : type " + type.getSimpleName());
            if (findAccessor(objectType, field.getName(), "set", false) == null) {
                System.out.print(" (readonly)");
            }
        }
    }
    System.out.println("");
    if (!type.isPrimitive())
        printFieldDetails(type, indent);
}

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

/**
 * <p>/*w w  w  .  j av a  2 s . c o  m*/
 * changeClassLoader
 * </p>
 * 
 * @param loader
 *            a {@link java.lang.ClassLoader} object.
 */
public void changeClassLoader(ClassLoader loader) {
    try {
        if (rawClass != null)
            rawClass = getClass(rawClass.getName(), loader);
        if (type instanceof ParameterizedType) {
            ParameterizedType pt = (ParameterizedType) type;
            // GenericClass rawType = new GenericClass(pt.getRawType());
            // rawType.changeClassLoader(loader);
            GenericClass ownerType = null;
            if (pt.getOwnerType() != null) {
                ownerType = new GenericClass(pt.getOwnerType());
                // ownerType.type = pt.getOwnerType();
                ownerType.changeClassLoader(loader);
            }
            List<GenericClass> parameterClasses = new ArrayList<GenericClass>();
            for (Type parameterType : pt.getActualTypeArguments()) {
                GenericClass parameter = new GenericClass(parameterType);
                // parameter.type = parameterType;
                parameter.changeClassLoader(loader);
                parameterClasses.add(parameter);
            }
            Type[] parameterTypes = new Type[parameterClasses.size()];
            for (int i = 0; i < parameterClasses.size(); i++)
                parameterTypes[i] = parameterClasses.get(i).getType();
            this.type = new ParameterizedTypeImpl(rawClass, parameterTypes,
                    ownerType != null ? ownerType.getType() : null);
        } else if (type instanceof GenericArrayType) {
            GenericClass componentClass = getComponentClass();
            componentClass.changeClassLoader(loader);
            this.type = GenericArrayTypeImpl.createArrayType(componentClass.getType());
        } else if (type instanceof WildcardType) {
            Type[] oldUpperBounds = ((WildcardType) type).getUpperBounds();
            Type[] oldLowerBounds = ((WildcardType) type).getLowerBounds();
            Type[] upperBounds = new Type[oldUpperBounds.length];
            Type[] lowerBounds = new Type[oldLowerBounds.length];

            for (int i = 0; i < oldUpperBounds.length; i++) {
                GenericClass bound = new GenericClass(oldUpperBounds[i]);
                // bound.type = oldUpperBounds[i];
                bound.changeClassLoader(loader);
                upperBounds[i] = bound.getType();
            }
            for (int i = 0; i < oldLowerBounds.length; i++) {
                GenericClass bound = new GenericClass(oldLowerBounds[i]);
                // bound.type = oldLowerBounds[i];
                bound.changeClassLoader(loader);
                lowerBounds[i] = bound.getType();
            }
            this.type = new WildcardTypeImpl(upperBounds, lowerBounds);
        } else if (type instanceof TypeVariable<?>) {
            for (TypeVariable<?> newVar : rawClass.getTypeParameters()) {
                if (newVar.getName().equals(((TypeVariable<?>) type).getName())) {
                    this.type = newVar;
                    break;
                }
            }
        } else {
            this.type = addTypeParameters(rawClass); //GenericTypeReflector.addWildcardParameters(raw_class);
        }
    } catch (ClassNotFoundException e) {
        logger.warn("Class not found: {} - keeping old class loader ", rawClass, e);
    } catch (SecurityException e) {
        logger.warn("Class not found: {} - keeping old class loader ", rawClass, e);
    }
}

From source file:org.apache.flink.api.java.typeutils.TypeExtractor.java

/**
 * Creates the TypeInformation for all elements of a type that expects a certain number of
 * subtypes (e.g. TupleXX).//from   ww w  . j a  v  a 2 s . c o  m
 *
 * @param originalType most concrete subclass
 * @param definingType type that defines the number of subtypes (e.g. Tuple2 -> 2 subtypes)
 * @param typeHierarchy necessary for type inference
 * @param in1Type necessary for type inference
 * @param in2Type necessary for type inference
 * @param lenient decides whether exceptions should be thrown if a subtype can not be determined
 * @return array containing TypeInformation of sub types or null if definingType contains
 *     more subtypes (fields) that defined
 */
private <IN1, IN2> TypeInformation<?>[] createSubTypesInfo(Type originalType, ParameterizedType definingType,
        ArrayList<Type> typeHierarchy, TypeInformation<IN1> in1Type, TypeInformation<IN2> in2Type,
        boolean lenient) {
    Type[] subtypes = new Type[definingType.getActualTypeArguments().length];

    // materialize possible type variables
    for (int i = 0; i < subtypes.length; i++) {
        final Type actualTypeArg = definingType.getActualTypeArguments()[i];
        // materialize immediate TypeVariables
        if (actualTypeArg instanceof TypeVariable<?>) {
            subtypes[i] = materializeTypeVariable(typeHierarchy, (TypeVariable<?>) actualTypeArg);
        }
        // class or parameterized type
        else {
            subtypes[i] = actualTypeArg;
        }
    }

    TypeInformation<?>[] subTypesInfo = new TypeInformation<?>[subtypes.length];
    for (int i = 0; i < subtypes.length; i++) {
        final ArrayList<Type> subTypeHierarchy = new ArrayList<>(typeHierarchy);
        subTypeHierarchy.add(subtypes[i]);
        // sub type could not be determined with materializing
        // try to derive the type info of the TypeVariable from the immediate base child input as a last attempt
        if (subtypes[i] instanceof TypeVariable<?>) {
            subTypesInfo[i] = createTypeInfoFromInputs((TypeVariable<?>) subtypes[i], subTypeHierarchy, in1Type,
                    in2Type);

            // variable could not be determined
            if (subTypesInfo[i] == null && !lenient) {
                throw new InvalidTypesException("Type of TypeVariable '"
                        + ((TypeVariable<?>) subtypes[i]).getName() + "' in '"
                        + ((TypeVariable<?>) subtypes[i]).getGenericDeclaration()
                        + "' could not be determined. This is most likely a type erasure problem. "
                        + "The type extraction currently supports types with generic variables only in cases where "
                        + "all variables in the return type can be deduced from the input type(s).");
            }
        } else {
            // create the type information of the subtype or null/exception
            try {
                subTypesInfo[i] = createTypeInfoWithTypeHierarchy(subTypeHierarchy, subtypes[i], in1Type,
                        in2Type);
            } catch (InvalidTypesException e) {
                if (lenient) {
                    subTypesInfo[i] = null;
                } else {
                    throw e;
                }
            }
        }
    }

    // check that number of fields matches the number of subtypes
    if (!lenient) {
        Class<?> originalTypeAsClass = null;
        if (isClassType(originalType)) {
            originalTypeAsClass = typeToClass(originalType);
        }
        checkNotNull(originalTypeAsClass, "originalType has an unexpected type");
        // check if the class we assumed to conform to the defining type so far is actually a pojo because the
        // original type contains additional fields.
        // check for additional fields.
        int fieldCount = countFieldsInClass(originalTypeAsClass);
        if (fieldCount > subTypesInfo.length) {
            return null;
        }
    }

    return subTypesInfo;
}

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

/**
 * <p>/*from  w  w w .ja v a  2  s.  c  om*/
 * changeClassLoader
 * </p>
 * 
 * @param loader
 *            a {@link java.lang.ClassLoader} object.
 */
public void changeClassLoader(ClassLoader loader) {
    try {
        if (rawClass != null)
            rawClass = getClass(rawClass.getName(), loader);
        if (type instanceof ParameterizedType) {
            ParameterizedType pt = (ParameterizedType) type;
            // GenericClass rawType = new GenericClass(pt.getRawType());
            // rawType.changeClassLoader(loader);
            GenericClass ownerType = null;
            if (pt.getOwnerType() != null) {
                ownerType = new GenericClass(pt.getOwnerType());
                // ownerType.type = pt.getOwnerType();
                ownerType.changeClassLoader(loader);
            }
            List<GenericClass> parameterClasses = new ArrayList<GenericClass>();
            for (Type parameterType : pt.getActualTypeArguments()) {
                GenericClass parameter = new GenericClass(parameterType);
                // parameter.type = parameterType;
                parameter.changeClassLoader(loader);
                parameterClasses.add(parameter);
            }
            Type[] parameterTypes = new Type[parameterClasses.size()];
            for (int i = 0; i < parameterClasses.size(); i++)
                parameterTypes[i] = parameterClasses.get(i).getType();
            this.type = new ParameterizedTypeImpl(rawClass, parameterTypes,
                    ownerType != null ? ownerType.getType() : null);
        } else if (type instanceof GenericArrayType) {
            GenericClass componentClass = getComponentClass();
            componentClass.changeClassLoader(loader);
            this.type = GenericArrayTypeImpl.createArrayType(componentClass.getType());
        } else if (type instanceof WildcardType) {
            Type[] oldUpperBounds = ((WildcardType) type).getUpperBounds();
            Type[] oldLowerBounds = ((WildcardType) type).getLowerBounds();
            Type[] upperBounds = new Type[oldUpperBounds.length];
            Type[] lowerBounds = new Type[oldLowerBounds.length];

            for (int i = 0; i < oldUpperBounds.length; i++) {
                GenericClass bound = new GenericClass(oldUpperBounds[i]);
                // bound.type = oldUpperBounds[i];
                bound.changeClassLoader(loader);
                upperBounds[i] = bound.getType();
            }
            for (int i = 0; i < oldLowerBounds.length; i++) {
                GenericClass bound = new GenericClass(oldLowerBounds[i]);
                // bound.type = oldLowerBounds[i];
                bound.changeClassLoader(loader);
                lowerBounds[i] = bound.getType();
            }
            this.type = new WildcardTypeImpl(upperBounds, lowerBounds);
        } else if (type instanceof TypeVariable<?>) {
            for (TypeVariable<?> newVar : rawClass.getTypeParameters()) {
                if (newVar.getName().equals(((TypeVariable<?>) type).getName())) {
                    this.type = newVar;
                    break;
                }
            }
        } else {
            this.type = addTypeParameters(rawClass); //GenericTypeReflector.addWildcardParameters(raw_class);
        }
    } catch (ClassNotFoundException e) {
        logger.warn("Class not found: " + rawClass + " - keeping old class loader ", e);
    } catch (SecurityException e) {
        logger.warn("Class not found: " + rawClass + " - keeping old class loader ", e);
    }
}

From source file:org.fornax.cartridges.sculptor.smartclient.server.ScServlet.java

private void mapRequestToObj(HashMap<String, Object> data, Class expectedClass, Object obj) throws Exception {
    if (obj == null) {
        throw new ApplicationException("mapRequestToObj called on NULL obj", "ERR9001");
    }/*from w ww .  j a va  2  s. c om*/

    try {
        Method versionMethod = expectedClass.getMethod("getVersion", (Class<?>[]) null);
        Long objVersion = (Long) versionMethod.invoke(obj, (Object[]) null);
        String clientVersion = (String) data.get("version");
        if (objVersion != null && clientVersion != null) {
            try {
                long clientVersionLong = Long.parseLong(clientVersion);
                if (!objVersion.equals(clientVersionLong)) {
                    throw makeApplicationException("Can't save object", "ERR9016", (Serializable[]) null);
                }
            } catch (NumberFormatException nfe) {
                // Version from client isn't number - ignore
            }
        }
    } catch (NoSuchMethodException nme) {
        // No version control
    }

    Method[] methods = expectedClass.getMethods();
    for (Method m : methods) {
        Class<?>[] paramTypes = m.getParameterTypes();

        Class persistentClass = null;
        if (paramTypes.length == 1) {
            if (paramTypes[0].getAnnotation(Entity.class) != null) {
                persistentClass = paramTypes[0];
            } else if (paramTypes[0].getAnnotation(Embeddable.class) != null) {
                persistentClass = paramTypes[0];
            }
        }
        ServiceDescription srvParam = paramTypes.length == 1 ? findServiceByClassName(paramTypes[0].getName())
                : null;
        if ((m.getName().startsWith(SET_PREFIX) && paramTypes.length == 1
                && (paramTypes[0].isAssignableFrom(String.class) || paramTypes[0].equals(Integer.class)
                        || paramTypes[0].equals(Integer.TYPE) || paramTypes[0].equals(Long.class)
                        || paramTypes[0].equals(Long.TYPE) || paramTypes[0].equals(Float.class)
                        || paramTypes[0].equals(Float.TYPE) || paramTypes[0].equals(Boolean.class)
                        || paramTypes[0].equals(Boolean.TYPE) || paramTypes[0].equals(Double.class)
                        || paramTypes[0].equals(Double.TYPE) || paramTypes[0].equals(Date.class)
                        || Enum.class.isAssignableFrom(paramTypes[0])
                        || (srvParam != null && srvParam.getFindById() != null) || persistentClass != null))
                || (m.getName().startsWith(GET_PREFIX) && paramTypes.length == 0
                        && (Set.class.isAssignableFrom(m.getReturnType())
                                || List.class.isAssignableFrom(m.getReturnType())))) {
            String fldName;
            if (m.getName().startsWith(GET_TRANSLATE)) {
                fldName = m.getName().substring(GET_TRANSLATE_LENGTH, GET_TRANSLATE_LENGTH + 1).toLowerCase()
                        + m.getName().substring(GET_TRANSLATE_LENGTH + 1);
            } else {
                fldName = m.getName().substring(3, 4).toLowerCase() + m.getName().substring(4);
            }
            Object value = data.get(fldName);
            if (value == null) {
                fldName = m.getName().substring(3);
                value = data.get(fldName);
            }
            if (value != null) {
                Object typedVal;
                String val = null;
                if (value instanceof String) {
                    val = (String) value;
                }
                log.log(Level.FINER, "        value = " + value);
                if (m.getName().startsWith(GET_PREFIX) && paramTypes.length == 0
                        && (Set.class.isAssignableFrom(m.getReturnType())
                                || List.class.isAssignableFrom(m.getReturnType()))) {
                    log.log(Level.FINER, "GET");

                    String attrName = m.getName().substring(3, 4).toLowerCase() + m.getName().substring(4);
                    Type[] actualTypeArguments = null;
                    Class iterClass = expectedClass;
                    while (iterClass != null) {
                        try {
                            Field field = iterClass.getDeclaredField(attrName);
                            ParameterizedType genericType = (ParameterizedType) field.getGenericType();
                            actualTypeArguments = genericType.getActualTypeArguments();
                            break;
                        } catch (NoSuchFieldException nsfe) {
                            // do nothing iterate again
                        }
                        iterClass = iterClass.getSuperclass();
                        iterClass = iterClass.equals(Object.class) ? null : iterClass;
                    }

                    if (actualTypeArguments != null && actualTypeArguments.length == 1
                            && actualTypeArguments[0] instanceof Class) {
                        Class assocClass = (Class) actualTypeArguments[0];
                        ServiceDescription assocService = findServiceByClassName(assocClass.getName());
                        Collection dbValueSet = (Collection) m.invoke(obj, (Object[]) null);
                        if (value == null || !(value instanceof HashMap)) {
                            log.log(Level.FINE, "No data for db property {0}", attrName);
                        } else if (assocService != null) {
                            HashMap<String, Object> guiValueMap = (HashMap<String, Object>) value;

                            ArrayList<Object> removeIt = new ArrayList<Object>();
                            Iterator dbIterator = dbValueSet.iterator();
                            while (dbIterator.hasNext()) {
                                Object dbVal = dbIterator.next();
                                String dbValId = getIdFromObj(dbVal);

                                if (dbValId != null) {
                                    boolean wasMatchingGuiVal = false;
                                    ArrayList<String> removeKeys = new ArrayList<String>();
                                    for (String key : guiValueMap.keySet()) {
                                        Object object = guiValueMap.get(key);
                                        if (object instanceof HashMap) {
                                            Object guiValue = ((HashMap<String, Object>) object).get("id");
                                            if (guiValue.equals(dbValId)) {
                                                removeKeys.add(key);
                                                wasMatchingGuiVal = true;
                                                mapRequestToObj((HashMap<String, Object>) guiValue, assocClass,
                                                        dbVal);
                                                break;
                                            }
                                        } else if (object instanceof String) {
                                            // Association
                                            if (dbValId.equals(object)) {
                                                removeKeys.add(key);
                                                wasMatchingGuiVal = true;
                                            }
                                        } else {
                                            log.log(Level.WARNING, "Wrong object type from GUI under key {0}",
                                                    key);
                                        }
                                    }
                                    // Remove processed elements
                                    // Direct remove is firing concurrent modification exception
                                    for (String removeKey : removeKeys) {
                                        guiValueMap.remove(removeKey);
                                    }

                                    if (!wasMatchingGuiVal) {
                                        // Is not in list comming from GUI - delete
                                        removeIt.add(dbVal);
                                    }
                                } else {
                                    log.log(Level.WARNING, "No ID in object {0}", dbVal);
                                }
                            }
                            dbValueSet.removeAll(removeIt);

                            // Rest are new records
                            for (String key : guiValueMap.keySet()) {
                                Object object = guiValueMap.get(key);
                                if (object instanceof HashMap) {
                                    Object subObj = makeNewInstance(assocClass,
                                            (HashMap<String, Object>) object);
                                    mapRequestToObj((HashMap<String, Object>) object, assocClass, subObj);
                                    dbValueSet.add(subObj);
                                } else if (object instanceof String) {
                                    // Association
                                    try {
                                        Long id = new Long((String) object);
                                        Object assocObj = assocService.getFindById().invoke(
                                                assocService.getInstance(), ServiceContextStore.get(), id);
                                        if (assocObj != null) {
                                            dbValueSet.add(assocObj);
                                        } else {
                                            log.log(Level.WARNING,
                                                    "Object with ID {0} not availabla via service {1}",
                                                    new Object[] { id, assocService.getName() });
                                        }
                                    } catch (Exception ex) {
                                        log.log(Level.WARNING, "No ID parsable from value {0} under key {1}",
                                                new Object[] { object, key });
                                    }
                                } else {
                                    log.log(Level.WARNING, "Wrong sub type {0}", attrName);
                                }
                            }
                        } else if (assocClass != null) {
                            HashMap<String, Object> guiValueMap = (HashMap<String, Object>) value;

                            ArrayList<Object> removeIt = new ArrayList<Object>();
                            Iterator dbIterator = dbValueSet.iterator();
                            while (dbIterator.hasNext()) {
                                Object dbVal = dbIterator.next();
                                String dbValId = getIdFromObj(dbVal);

                                if (dbValId != null) {
                                    Object matchingGuiVal = null;
                                    for (String key : guiValueMap.keySet()) {
                                        Object object = guiValueMap.get(key);
                                        if (object instanceof HashMap) {
                                            HashMap<String, Object> guiVal = (HashMap<String, Object>) object;
                                            if (dbValId.equals(guiVal.get("id"))) {
                                                guiValueMap.remove(key);
                                                matchingGuiVal = guiVal;
                                                break;
                                            }
                                        } else {
                                            log.log(Level.WARNING, "Wrong object type from GUI under key {0}",
                                                    key);
                                        }
                                    }
                                    if (matchingGuiVal != null) {
                                        // Coming from GUI - update
                                        mapRequestToObj((HashMap<String, Object>) matchingGuiVal, assocClass,
                                                dbVal);
                                    } else {
                                        // Not in GUI - delete
                                        removeIt.add(dbVal);
                                    }
                                } else {
                                    log.log(Level.WARNING, "No ID in object {0}", dbVal);
                                }
                            }
                            dbValueSet.removeAll(removeIt);

                            // Rest are new records
                            for (String key : guiValueMap.keySet()) {
                                Object object = guiValueMap.get(key);
                                if (object instanceof HashMap) {
                                    Object subObj = makeNewInstance(assocClass,
                                            (HashMap<String, Object>) object);
                                    mapRequestToObj((HashMap<String, Object>) object, assocClass, subObj);
                                    dbValueSet.add(subObj);
                                } else {
                                    log.log(Level.WARNING, "Wrong sub type {0}", attrName);
                                }
                            }
                        }
                    } else {
                        log.log(Level.WARNING, "No DB mapping or not of collection type: {0}", attrName);
                    }
                    typedVal = null;
                } else if (paramTypes[0].isAssignableFrom(String.class)) {
                    typedVal = val;
                } else if (paramTypes[0].equals(Integer.class) || paramTypes[0].equals(Integer.TYPE)) {
                    typedVal = Integer.parseInt(val);
                } else if (paramTypes[0].equals(Long.class) || paramTypes[0].equals(Long.TYPE)) {
                    typedVal = Long.parseLong(val);
                } else if (paramTypes[0].equals(Double.class) || paramTypes[0].equals(Double.TYPE)) {
                    typedVal = Double.parseDouble(val);
                } else if (paramTypes[0].equals(Float.class) || paramTypes[0].equals(Float.TYPE)) {
                    typedVal = Float.parseFloat(val);
                } else if (paramTypes[0].equals(Boolean.class) || paramTypes[0].equals(Boolean.TYPE)) {
                    typedVal = "true".equalsIgnoreCase(val) || "t".equalsIgnoreCase(val)
                            || "y".equalsIgnoreCase(val);
                } else if (paramTypes[0].isAssignableFrom(Date.class)) {
                    typedVal = dateFormat.parse(val);
                } else if (Enum.class.isAssignableFrom(paramTypes[0])) {
                    try {
                        Method fromValueMethod = paramTypes[0].getMethod("fromValue", String.class);
                        typedVal = fromValueMethod.invoke(null, val);
                    } catch (Exception ex) {
                        typedVal = null;
                    }

                    try {
                        if (typedVal == null) {
                            Method valueOfMethod = paramTypes[0].getMethod("valueOf", String.class);
                            typedVal = valueOfMethod.invoke(null, val);
                        }
                    } catch (Exception ex) {
                        typedVal = null;
                    }
                } else if (persistentClass != null && persistentClass.equals(FileUpload.class)) {
                    FileItem fileItem = uploadServlet.getFileItem(sessionId.get(), fldName, val);
                    if (fileItem != null) {
                        typedVal = fileUploadService.uploadFile(ServiceContextStore.get(), fileItem.getName(),
                                fileItem.getContentType(), fileItem.getInputStream());
                    } else {
                        typedVal = null;
                    }
                } else if (srvParam != null && srvParam.getFindById() != null) {
                    if (value instanceof HashMap) {
                        HashMap<String, Object> embeddedObj = (HashMap<String, Object>) value;
                        typedVal = srvParam.getFindById().invoke(srvParam.getInstance(),
                                ServiceContextStore.get(), new Long((String) embeddedObj.get("id")));
                        mapRequestToObj(embeddedObj, srvParam.getExpectedClass(), typedVal);
                    } else {
                        try {
                            Long parsedId = new Long(val);
                            typedVal = srvParam.getFindById().invoke(srvParam.getInstance(),
                                    ServiceContextStore.get(), parsedId);
                        } catch (NumberFormatException nfe) {
                            // wrong value
                            typedVal = null;
                        }
                    }
                } else if (persistentClass != null) {
                    String getMethodName = "g" + m.getName().substring(1);
                    try {
                        Method getMethod = obj.getClass().getMethod(getMethodName, (Class[]) null);
                        typedVal = getMethod.invoke(obj, (Object[]) null);
                    } catch (NoSuchMethodException nsme) {
                        typedVal = null;
                    }
                    if (typedVal == null) {
                        typedVal = makeNewInstance(persistentClass, (HashMap<String, Object>) value);
                    }
                    mapRequestToObj((HashMap<String, Object>) value, typedVal.getClass(), typedVal);
                } else {
                    log.log(Level.WARNING, "Can't convert value for: {0}.{1} ({2})", new Object[] {
                            expectedClass.getName(), m.getName(),
                            (paramTypes.length == 1 ? paramTypes[0].getName() : paramTypes.toString()) });
                    typedVal = null;
                }
                if (typedVal != null) {
                    m.invoke(obj, typedVal);
                }
            }
        } else if (m.getName().startsWith(SET_PREFIX)) {
            log.log(Level.WARNING, "Unusable setter method: {0}.{1} ({2})",
                    new Object[] { expectedClass.getName(), m.getName(),
                            (paramTypes.length == 1 ? paramTypes[0].getName() : paramTypes.toString()) });
        }
    }
}

From source file:org.apache.flink.api.java.typeutils.TypeExtractor.java

private <IN1, IN2> TypeInformation<?> createTypeInfoFromInputs(TypeVariable<?> returnTypeVar,
        ArrayList<Type> returnTypeHierarchy, TypeInformation<IN1> in1TypeInfo,
        TypeInformation<IN2> in2TypeInfo) {

    Type matReturnTypeVar = materializeTypeVariable(returnTypeHierarchy, returnTypeVar);

    // variable could be resolved
    if (!(matReturnTypeVar instanceof TypeVariable)) {
        return createTypeInfoWithTypeHierarchy(returnTypeHierarchy, matReturnTypeVar, in1TypeInfo, in2TypeInfo);
    } else {//from   w  ww.  ja v  a2  s . co  m
        returnTypeVar = (TypeVariable<?>) matReturnTypeVar;
    }

    // no input information exists
    if (in1TypeInfo == null && in2TypeInfo == null) {
        return null;
    }

    // create a new type hierarchy for the input
    ArrayList<Type> inputTypeHierarchy = new ArrayList<Type>();
    // copy the function part of the type hierarchy
    for (Type t : returnTypeHierarchy) {
        if (isClassType(t) && Function.class.isAssignableFrom(typeToClass(t))
                && typeToClass(t) != Function.class) {
            inputTypeHierarchy.add(t);
        } else {
            break;
        }
    }
    ParameterizedType baseClass = (ParameterizedType) inputTypeHierarchy.get(inputTypeHierarchy.size() - 1);

    TypeInformation<?> info = null;
    if (in1TypeInfo != null) {
        // find the deepest type variable that describes the type of input 1
        Type in1Type = baseClass.getActualTypeArguments()[0];

        info = createTypeInfoFromInput(returnTypeVar, new ArrayList<Type>(inputTypeHierarchy), in1Type,
                in1TypeInfo);
    }

    if (info == null && in2TypeInfo != null) {
        // find the deepest type variable that describes the type of input 2
        Type in2Type = baseClass.getActualTypeArguments()[1];

        info = createTypeInfoFromInput(returnTypeVar, new ArrayList<Type>(inputTypeHierarchy), in2Type,
                in2TypeInfo);
    }

    if (info != null) {
        return info;
    }

    return null;
}

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

public Class findResultActualType() {
    // TODO: Fix this!  it isn't doing the right thing for DBC as noted below with FIXME comments
    //       This is used to marshall the rsp on the service (dbc) and demarshall on the client (reflection)
    //       But we shouldn't get an async OpDesc on the service since getDispatchableOperation(QN) removes them.

    Class returnType = getResultType();
    if (returnType == null) {
        return null;
    }/*from  ww w.  j a  v a  2 s. c o  m*/
    if (isJAXWSAsyncClientMethod()) {
        //pooling implementation
        if (Response.class == returnType) {
            if (!isDBC()) {
                Type type = seiMethod.getGenericReturnType();
                ParameterizedType pType = (ParameterizedType) type;
                Type aType = pType.getActualTypeArguments()[0];
                if (aType != null && ParameterizedType.class.isInstance(aType)) {
                    return (Class) ((ParameterizedType) aType).getRawType();
                }
                return (Class) aType;
            } else {
                // FIXME: This doesn't work for DBC.  That's OK for now because DBC isn't used on the client side
                //        yet; the client is all Java Reflection.  On the Service side, the Async methods are not used.
                //        This needs to return T for Response<T>, or List for Response<List<T>>>
                return returnType;
            }
        }
        //Callback Implementation
        else {
            // FIXME: This doesn't work for DBC.  That's OK for now because DBC isn't used on the client side
            //        yet; the client is all Java Reflection.  On the Service side, the Async methods are not used.
            //        This needs to find and return T for AsyncHandler<T>, or List for AsyncHandler<List<T>>>
            Type[] type = getGenericParameterTypes();
            Class parameters[] = getParameterTypes();
            int i = 0;
            for (Class param : parameters) {
                if (AsyncHandler.class.isAssignableFrom(param)) {
                    ParameterizedType pType = (ParameterizedType) type[i];
                    Type aType = pType.getActualTypeArguments()[0];
                    if (aType != null && ParameterizedType.class.isInstance(aType)) {
                        return (Class) ((ParameterizedType) aType).getRawType();
                    }
                    return (Class) aType;
                }
                i++;
            }
        }
    }

    return returnType;
}

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

/**
 * If this is a LinkedList<?> and the super class is a List<Integer> then
 * this returns a LinkedList<Integer>
 * //from  w  w  w.  ja  va2s .  co  m
 * @param superClass
 * @return
 * @throws ConstructionFailedException
 */
public GenericClass getWithParametersFromSuperclass(GenericClass superClass)
        throws ConstructionFailedException {
    GenericClass exactClass = new GenericClass(type);
    if (!(type instanceof ParameterizedType)) {
        exactClass.type = type;
        return exactClass;
    }
    ParameterizedType pType = (ParameterizedType) type;

    if (superClass.isParameterizedType()) {
        Map<TypeVariable<?>, Type> typeMap = TypeUtils.determineTypeArguments(rawClass,
                (ParameterizedType) superClass.getType());
        return getGenericInstantiation(typeMap);
    }

    Class<?> targetClass = superClass.getRawClass();
    Class<?> currentClass = rawClass;
    Type[] parameterTypes = new Type[superClass.getNumParameters()];
    superClass.getParameterTypes().toArray(parameterTypes);

    if (targetClass.equals(currentClass)) {
        logger.info("Raw classes match, setting parameters to: {}", superClass.getParameterTypes());
        exactClass.type = new ParameterizedTypeImpl(currentClass, parameterTypes, pType.getOwnerType());
    } else {
        Type ownerType = pType.getOwnerType();
        Map<TypeVariable<?>, Type> superTypeMap = superClass.getTypeVariableMap();
        Type[] origArguments = pType.getActualTypeArguments();
        Type[] arguments = Arrays.copyOf(origArguments, origArguments.length);
        List<TypeVariable<?>> variables = getTypeVariables();
        for (int i = 0; i < arguments.length; i++) {
            TypeVariable<?> var = variables.get(i);
            if (superTypeMap.containsKey(var)) {
                arguments[i] = superTypeMap.get(var);
                logger.info("Setting type variable {} to {}", var, superTypeMap.get(var));
            } else if (arguments[i] instanceof WildcardType && i < parameterTypes.length) {
                logger.info("Replacing wildcard with {}", parameterTypes[i]);
                logger.info("Lower Bounds: {}",
                        Arrays.asList(TypeUtils.getImplicitLowerBounds((WildcardType) arguments[i])));
                logger.info("Upper Bounds: {}",
                        Arrays.asList(TypeUtils.getImplicitUpperBounds((WildcardType) arguments[i])));
                logger.info("Type variable: {}", variables.get(i));
                if (!TypeUtils.isAssignable(parameterTypes[i], arguments[i])) {
                    logger.info("Not assignable to bounds!");
                    return null;
                } else {
                    boolean assignable = false;
                    for (Type bound : variables.get(i).getBounds()) {
                        if (TypeUtils.isAssignable(parameterTypes[i], bound)) {
                            assignable = true;
                            break;
                        }
                    }
                    if (!assignable) {
                        logger.info("Not assignable to type variable!");
                        return null;
                    }
                }
                arguments[i] = parameterTypes[i];
            }
        }
        GenericClass ownerClass = new GenericClass(ownerType).getWithParametersFromSuperclass(superClass);
        if (ownerClass == null)
            return null;
        exactClass.type = new ParameterizedTypeImpl(currentClass, arguments, ownerClass.getType());
    }

    return exactClass;
}