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.apache.flink.api.java.typeutils.TypeExtractor.java

/**
 * Finds the type information to a type variable.
 *
 * It solve the following:/*from   w  w w .jav a 2 s  .  co m*/
 *
 * Return the type information for "returnTypeVar" given that "inType" has type information "inTypeInfo".
 * Thus "inType" must contain "returnTypeVar" in a "inputTypeHierarchy", otherwise null is returned.
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
private <IN1> TypeInformation<?> createTypeInfoFromInput(TypeVariable<?> returnTypeVar,
        ArrayList<Type> inputTypeHierarchy, Type inType, TypeInformation<IN1> inTypeInfo) {
    TypeInformation<?> info = null;

    // use a factory to find corresponding type information to type variable
    final ArrayList<Type> factoryHierarchy = new ArrayList<>(inputTypeHierarchy);
    final TypeInfoFactory<?> factory = getClosestFactory(factoryHierarchy, inType);
    if (factory != null) {
        // the type that defines the factory is last in factory hierarchy
        final Type factoryDefiningType = factoryHierarchy.get(factoryHierarchy.size() - 1);
        // defining type has generics, the factory need to be asked for a mapping of subtypes to type information
        if (factoryDefiningType instanceof ParameterizedType) {
            final Type[] typeParams = typeToClass(factoryDefiningType).getTypeParameters();
            final Type[] actualParams = ((ParameterizedType) factoryDefiningType).getActualTypeArguments();
            // go thru all elements and search for type variables
            for (int i = 0; i < actualParams.length; i++) {
                final Map<String, TypeInformation<?>> componentInfo = inTypeInfo.getGenericParameters();
                final String typeParamName = typeParams[i].toString();
                if (!componentInfo.containsKey(typeParamName) || componentInfo.get(typeParamName) == null) {
                    throw new InvalidTypesException("TypeInformation '" + inTypeInfo.getClass().getSimpleName()
                            + "' does not supply a mapping of TypeVariable '" + typeParamName
                            + "' to corresponding TypeInformation. "
                            + "Input type inference can only produce a result with this information. "
                            + "Please implement method 'TypeInformation.getGenericParameters()' for this.");
                }
                info = createTypeInfoFromInput(returnTypeVar, factoryHierarchy, actualParams[i],
                        componentInfo.get(typeParamName));
                if (info != null) {
                    break;
                }
            }
        }
    }
    // the input is a type variable
    else if (sameTypeVars(inType, returnTypeVar)) {
        return inTypeInfo;
    } else if (inType instanceof TypeVariable) {
        Type resolvedInType = materializeTypeVariable(inputTypeHierarchy, (TypeVariable<?>) inType);
        if (resolvedInType != inType) {
            info = createTypeInfoFromInput(returnTypeVar, inputTypeHierarchy, resolvedInType, inTypeInfo);
        }
    }
    // input is an array
    else if (inType instanceof GenericArrayType) {
        TypeInformation<?> componentInfo = null;
        if (inTypeInfo instanceof BasicArrayTypeInfo) {
            componentInfo = ((BasicArrayTypeInfo<?, ?>) inTypeInfo).getComponentInfo();
        } else if (inTypeInfo instanceof PrimitiveArrayTypeInfo) {
            componentInfo = BasicTypeInfo.getInfoFor(inTypeInfo.getTypeClass().getComponentType());
        } else if (inTypeInfo instanceof ObjectArrayTypeInfo) {
            componentInfo = ((ObjectArrayTypeInfo<?, ?>) inTypeInfo).getComponentInfo();
        }
        info = createTypeInfoFromInput(returnTypeVar, inputTypeHierarchy,
                ((GenericArrayType) inType).getGenericComponentType(), componentInfo);
    }
    // the input is a tuple
    else if (inTypeInfo instanceof TupleTypeInfo && isClassType(inType)
            && Tuple.class.isAssignableFrom(typeToClass(inType))) {
        ParameterizedType tupleBaseClass;

        // get tuple from possible tuple subclass
        while (!(isClassType(inType) && typeToClass(inType).getSuperclass().equals(Tuple.class))) {
            inputTypeHierarchy.add(inType);
            inType = typeToClass(inType).getGenericSuperclass();
        }
        inputTypeHierarchy.add(inType);

        // we can assume to be parameterized since we
        // already did input validation
        tupleBaseClass = (ParameterizedType) inType;

        Type[] tupleElements = tupleBaseClass.getActualTypeArguments();
        // go thru all tuple elements and search for type variables
        for (int i = 0; i < tupleElements.length; i++) {
            info = createTypeInfoFromInput(returnTypeVar, inputTypeHierarchy, tupleElements[i],
                    ((TupleTypeInfo<?>) inTypeInfo).getTypeAt(i));
            if (info != null) {
                break;
            }
        }
    }
    // the input is a pojo
    else if (inTypeInfo instanceof PojoTypeInfo && isClassType(inType)) {
        // build the entire type hierarchy for the pojo
        getTypeHierarchy(inputTypeHierarchy, inType, Object.class);
        // determine a field containing the type variable
        List<Field> fields = getAllDeclaredFields(typeToClass(inType), false);
        for (Field field : fields) {
            Type fieldType = field.getGenericType();
            if (fieldType instanceof TypeVariable && sameTypeVars(returnTypeVar,
                    materializeTypeVariable(inputTypeHierarchy, (TypeVariable<?>) fieldType))) {
                return getTypeOfPojoField(inTypeInfo, field);
            } else if (fieldType instanceof ParameterizedType || fieldType instanceof GenericArrayType) {
                ArrayList<Type> typeHierarchyWithFieldType = new ArrayList<>(inputTypeHierarchy);
                typeHierarchyWithFieldType.add(fieldType);
                TypeInformation<?> foundInfo = createTypeInfoFromInput(returnTypeVar,
                        typeHierarchyWithFieldType, fieldType, getTypeOfPojoField(inTypeInfo, field));
                if (foundInfo != null) {
                    return foundInfo;
                }
            }
        }
    }
    return info;
}

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

/**
 * If this is a LinkedList<?> and the super class is a List<Integer> then
 * this returns a LinkedList<Integer>
 * /*ww  w. j av  a2  s . c o 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 = new Type[origArguments.length];
        // For some reason, doing this would lead to arguments being
        // of component type TypeVariable, which would lead to
        // ArrayStoreException if we try to assign a WildcardType
        //Type[] arguments = Arrays.copyOf(origArguments, origArguments.length);
        for (int i = 0; i < origArguments.length; i++)
            arguments[i] = origArguments[i];
        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 " + var + " to " + 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;
}

From source file:org.jakz.common.JSONObject.java

/**
 * DO NOT USE! This is just a sketch in development.
 * @param source//from www . j ava 2 s . com
 * @param target
 * @return
 * @throws IllegalArgumentException
 * @throws IllegalAccessException
 * @throws InstantiationException
 * @throws NoSuchMethodException
 * @throws SecurityException
 * @throws InvocationTargetException
 */
public static Object injectIntoPOJO(Object source, Object target)
        throws IllegalArgumentException, IllegalAccessException, InstantiationException, NoSuchMethodException,
        SecurityException, InvocationTargetException {
    if (source instanceof Byte || source instanceof Character || source instanceof Short
            || source instanceof Integer || source instanceof Long || source instanceof Boolean
            || source instanceof Float || source instanceof Double || source instanceof String
            || source instanceof BigInteger || source instanceof BigDecimal) {
        return source;
    }

    Class<?> pojoClass = null;
    if (target != null)
        pojoClass = target.getClass();
    else {
        pojoClass = source.getClass();
        target = pojoClass.newInstance();
    }

    Field[] field = pojoClass.getFields();
    Object toReturn = pojoClass.newInstance();
    for (int i = 0; i < field.length; i++) {
        String fieldName = field[i].getName();
        Class<?> fieldType = field[i].getType();
        ParameterizedType fieldParameterizedType = (ParameterizedType) field[i].getGenericType();

        if (source instanceof JSONObject) {
            JSONObject sjson = (JSONObject) source;
            if (fieldType == Integer.class || fieldType == Byte.class)
                field[i].set(target, sjson.getInt(fieldName));
            else if (fieldType == BigInteger.class || fieldType == Long.class)
                field[i].set(target, sjson.getBigInteger(fieldName));
            else if (fieldType == Boolean.class)
                field[i].set(target, sjson.getBoolean(fieldName));
            else if (fieldType == Double.class)
                field[i].set(target, sjson.getDouble(fieldName));
            else if (fieldType == String.class || fieldType == Character.class)
                field[i].set(target, sjson.getString(fieldName));
            else if (fieldType.isArray()) {
                JSONArray ajson = sjson.getJSONArray(fieldName);
                Object apojo = Array.newInstance(fieldType, ajson.length());
                Class<?> componentType = fieldType.getComponentType();
                for (int ai = 0; ai < ajson.length(); ai++) {
                    Object toAddValue = ajson.get(i);
                    Object componentPOJO = componentType.newInstance();
                    Array.set(apojo, ai, injectIntoPOJO(toAddValue, componentPOJO));
                }

                field[i].set(target, apojo);
            } else if (Collection.class.isAssignableFrom(fieldType)) {
                JSONArray ajson = sjson.getJSONArray(fieldName);
                Collection<?> cpojo = (Collection<?>) fieldType.newInstance();

                for (int ai = 0; ai < ajson.length(); ai++) {
                    Object toAddValue = ajson.get(i);
                    Class<?> genericType = (Class<?>) fieldParameterizedType.getActualTypeArguments()[0];
                    System.out.println("generic type: " + genericType.getName());
                    Object componentPOJO = genericType.newInstance(); //TODO - funkar inte
                    Method addMethod = fieldType.getMethod("add", Object.class);
                    addMethod.invoke(cpojo, injectIntoPOJO(toAddValue, componentPOJO));
                }

                field[i].set(target, cpojo);
            } else {
                try {
                    Object pojoInstance = fieldType.newInstance();
                    field[i].set(target, injectIntoPOJO(sjson.get(fieldName), pojoInstance));
                } catch (Exception e) {
                    throw new JSONException("Could not inject field " + fieldName + " of type "
                            + fieldType.getName() + " into POJO.", e);
                }
            }
        }

        //add more sources
    }

    return toReturn;
}

From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java

private void processRemovedManyToMany(ObjectsToPersist toPersist,
        Map<com.hiperf.common.ui.shared.util.Id, INakedObject> res, Map<Object, IdHolder> newIdByOldId,
        EntityManager em) throws ClassNotFoundException, IntrospectionException, PersistenceException,
        IllegalAccessException, InvocationTargetException, NoSuchFieldException {
    Map<String, Map<com.hiperf.common.ui.shared.util.Id, Map<String, List<com.hiperf.common.ui.shared.util.Id>>>> manyToManyRemoved = toPersist
            .getManyToManyRemovedByClassName();
    if (manyToManyRemoved != null && !manyToManyRemoved.isEmpty()) {
        for (Entry<String, Map<com.hiperf.common.ui.shared.util.Id, Map<String, List<com.hiperf.common.ui.shared.util.Id>>>> e : manyToManyRemoved
                .entrySet()) {/* ww  w .  ja  v a  2 s .  c  om*/
            String className = e.getKey();
            Map<com.hiperf.common.ui.shared.util.Id, Map<String, List<com.hiperf.common.ui.shared.util.Id>>> map = e
                    .getValue();
            if (map != null && !map.isEmpty()) {
                Class<?> clazz = Class.forName(className);
                for (Entry<com.hiperf.common.ui.shared.util.Id, Map<String, List<com.hiperf.common.ui.shared.util.Id>>> entry : map
                        .entrySet()) {
                    com.hiperf.common.ui.shared.util.Id id = entry.getKey();
                    Map<String, List<com.hiperf.common.ui.shared.util.Id>> m = entry.getValue();
                    if (m != null && !m.isEmpty()) {
                        Object objId = id.getFieldValues().get(0);
                        if (newIdByOldId.containsKey(objId))
                            objId = newIdByOldId.get(objId).getId();
                        Object o = em.find(clazz, objId);
                        if (o != null) {
                            PropertyDescriptor[] pds = propertyDescriptorsByClassName.get(className);
                            for (Entry<String, List<com.hiperf.common.ui.shared.util.Id>> ee : m.entrySet()) {
                                String attr = ee.getKey();
                                List<com.hiperf.common.ui.shared.util.Id> ll = ee.getValue();
                                if (ll != null && !ll.isEmpty()) {
                                    Collection coll = null;
                                    Class classInColl = null;
                                    PropertyDescriptor myPd = null;
                                    for (PropertyDescriptor pd : pds) {
                                        if (pd.getName().equals(attr)) {
                                            myPd = pd;
                                            coll = (Collection) pd.getReadMethod().invoke(o,
                                                    StorageService.emptyArg);
                                            break;
                                        }
                                    }
                                    if (coll != null) {
                                        ParameterizedType genericType = (ParameterizedType) clazz
                                                .getDeclaredField(myPd.getName()).getGenericType();
                                        if (genericType != null) {
                                            for (Type t : genericType.getActualTypeArguments()) {

                                                if (t instanceof Class
                                                        && INakedObject.class.isAssignableFrom((Class) t)) {
                                                    classInColl = (Class) t;
                                                    break;
                                                }
                                            }
                                        }
                                        for (com.hiperf.common.ui.shared.util.Id i : ll) {
                                            Object idObj = i.getFieldValues().get(0);
                                            if (newIdByOldId.containsKey(idObj))
                                                idObj = newIdByOldId.get(idObj);
                                            Object linkedObj = em.find(classInColl, idObj);
                                            coll.remove(linkedObj);
                                        }
                                    }
                                }
                            }
                            res.put(id, (INakedObject) em.merge(o));
                        }
                    }

                }
            }
        }
    }
}

From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java

private void processAddedManyToMany(ObjectsToPersist toPersist,
        Map<com.hiperf.common.ui.shared.util.Id, INakedObject> res, Map<Object, IdHolder> newIdByOldId,
        EntityManager em) throws ClassNotFoundException, IntrospectionException, PersistenceException,
        IllegalAccessException, InvocationTargetException, NoSuchFieldException {
    Map<String, Map<com.hiperf.common.ui.shared.util.Id, Map<String, List<com.hiperf.common.ui.shared.util.Id>>>> manyToManyAdded = toPersist
            .getManyToManyAddedByClassName();
    if (manyToManyAdded != null && !manyToManyAdded.isEmpty()) {
        for (Entry<String, Map<com.hiperf.common.ui.shared.util.Id, Map<String, List<com.hiperf.common.ui.shared.util.Id>>>> e : manyToManyAdded
                .entrySet()) {/*  w  ww.jav  a2  s  .  c  om*/
            String className = e.getKey();
            Map<com.hiperf.common.ui.shared.util.Id, Map<String, List<com.hiperf.common.ui.shared.util.Id>>> map = e
                    .getValue();
            if (map != null && !map.isEmpty()) {
                Class<?> clazz = Class.forName(className);
                for (Entry<com.hiperf.common.ui.shared.util.Id, Map<String, List<com.hiperf.common.ui.shared.util.Id>>> entry : map
                        .entrySet()) {
                    com.hiperf.common.ui.shared.util.Id id = entry.getKey();
                    Map<String, List<com.hiperf.common.ui.shared.util.Id>> m = entry.getValue();
                    if (m != null && !m.isEmpty()) {
                        Object objId = id.getFieldValues().get(0);
                        if (newIdByOldId.containsKey(objId))
                            objId = newIdByOldId.get(objId).getId();
                        Object o = em.find(clazz, objId);
                        if (o != null) {
                            PropertyDescriptor[] pds = propertyDescriptorsByClassName.get(className);
                            for (Entry<String, List<com.hiperf.common.ui.shared.util.Id>> ee : m.entrySet()) {
                                String attr = ee.getKey();
                                List<com.hiperf.common.ui.shared.util.Id> ll = ee.getValue();
                                if (ll != null && !ll.isEmpty()) {
                                    Collection coll = null;
                                    Class classInColl = null;
                                    PropertyDescriptor myPd = null;
                                    String mappedBy = null;
                                    for (PropertyDescriptor pd : pds) {
                                        if (pd.getName().equals(attr)) {
                                            myPd = pd;
                                            coll = (Collection) pd.getReadMethod().invoke(o,
                                                    StorageService.emptyArg);
                                            if (coll == null) {
                                                if (List.class.isAssignableFrom(pd.getPropertyType()))
                                                    coll = new ArrayList();
                                                else
                                                    coll = new HashSet();
                                                pd.getWriteMethod().invoke(o, coll);
                                            }
                                            ManyToMany ann = pd.getReadMethod().getAnnotation(ManyToMany.class);
                                            if (ann == null) {
                                                ann = clazz.getDeclaredField(pd.getName())
                                                        .getAnnotation(ManyToMany.class);
                                            }
                                            if (ann != null) {
                                                mappedBy = ann.mappedBy();
                                            }
                                            break;
                                        }
                                    }
                                    if (coll != null) {
                                        ParameterizedType genericType = (ParameterizedType) clazz
                                                .getDeclaredField(myPd.getName()).getGenericType();
                                        if (genericType != null) {
                                            for (Type t : genericType.getActualTypeArguments()) {

                                                if (t instanceof Class
                                                        && INakedObject.class.isAssignableFrom((Class) t)) {
                                                    classInColl = (Class) t;
                                                    break;
                                                }
                                            }
                                        }
                                        for (com.hiperf.common.ui.shared.util.Id i : ll) {
                                            Object idObj = i.getFieldValues().get(0);
                                            if (newIdByOldId.containsKey(idObj))
                                                idObj = newIdByOldId.get(idObj).getId();
                                            Object linkedObj = em.find(classInColl, idObj);
                                            if (mappedBy == null || mappedBy.length() == 0)
                                                coll.add(linkedObj);
                                            else {
                                                PropertyDescriptor[] pds2 = propertyDescriptorsByClassName
                                                        .get(classInColl.getName());
                                                if (pds2 == null) {
                                                    pds2 = propertyDescriptorsByClassName
                                                            .get(classInColl.getName());
                                                }
                                                for (PropertyDescriptor pd : collectionsByClassName
                                                        .get(classInColl.getName())) {
                                                    if (pd.getName().equals(mappedBy)) {
                                                        Collection coll2 = (Collection) pd.getReadMethod()
                                                                .invoke(linkedObj, StorageService.emptyArg);
                                                        if (coll2 == null) {
                                                            if (List.class
                                                                    .isAssignableFrom(pd.getPropertyType()))
                                                                coll2 = new ArrayList();
                                                            else
                                                                coll2 = new HashSet();
                                                            pd.getWriteMethod().invoke(linkedObj, coll2);
                                                        }
                                                        coll2.add(o);
                                                    }
                                                }
                                                em.merge(linkedObj);
                                            }
                                            if (linkedObj instanceof INakedObject)
                                                res.put(i, (INakedObject) linkedObj);
                                        }
                                    }
                                }
                            }
                            res.put(id, (INakedObject) em.merge(o));
                        }
                    }

                }
            }
        }
    }
}

From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java

@Override
public Map<String, String> getAll(String rootClassName, String filter, String attPrefix, String childClassName,
        String childAttribute) throws PersistenceException {
    EntityManager em = null;/*www. j  av  a  2 s  . c  om*/

    if (attPrefix != null && !attPrefix.isEmpty()) {
        String[] s = attPrefix.split("\\.");
        if (s == null || s.length == 0)
            s = new String[] { attPrefix };
        StringBuilder join = new StringBuilder();
        StringBuilder select = new StringBuilder();
        String lastClass = rootClassName;
        String lastJoinPrefix = "o.";
        int i = 0;
        for (int j = 0; j < s.length; j++) {
            String ss = s[j];
            PropertyDescriptor[] pds = propertyDescriptorsByClassName.get(lastClass);
            for (PropertyDescriptor pd : pds) {
                if (pd.getName().equals(ss)) {
                    Class<?> pt = pd.getPropertyType();
                    if (Collection.class.isAssignableFrom(pt) || INakedObject.class.isAssignableFrom(pt)) {

                        join.append(" inner join ").append(lastJoinPrefix);
                        if (!lastJoinPrefix.endsWith(".")) {
                            join.append(".");
                        }
                        join.append(ss).append(" y").append(i).append(" ");
                        lastJoinPrefix = "y" + i + ".";
                        i++;
                        if (Collection.class.isAssignableFrom(pt)) {
                            Class<?> clazz;
                            try {
                                clazz = Class.forName(lastClass);
                                ParameterizedType genericType = (ParameterizedType) clazz.getDeclaredField(ss)
                                        .getGenericType();
                                if (genericType != null) {
                                    for (Type t : genericType.getActualTypeArguments()) {

                                        if (t instanceof Class
                                                && INakedObject.class.isAssignableFrom((Class) t)) {
                                            lastClass = ((Class) t).getName();
                                            break;
                                        }
                                    }
                                }
                            } catch (Exception e) {
                                logger.log(Level.SEVERE, "Error", e);
                            }
                        } else {
                            lastClass = pt.getName();
                        }

                    } else if (childClassName.equals(pt.getName())) {
                        lastJoinPrefix += ss + ".";
                        if (i == s.length - 1) {
                            select.append("select ").append(lastJoinPrefix).append(childAttribute)
                                    .append(" from ").append(rootClassName).append(" o ");
                        }
                        lastClass = pt.getName();
                    } else {
                        lastJoinPrefix += ss + ".";
                        lastClass = pt.getName();
                    }
                    break;
                }
            }
        }
        HashMap<String, String> joinMap = null;
        if (join.length() > 0) {
            if (filter != null && !filter.isEmpty()) {
                int idx = filter.indexOf("inner join ");
                if (idx >= 0) {
                    joinMap = new HashMap<>();
                    String[] ff = filter.substring(idx + 11, filter.indexOf("where")).trim()
                            .split("inner join ");
                    for (String fj : ff) {
                        fj = fj.trim();
                        String[] fjj = fj.split(" ");
                        if (fjj.length == 2) {
                            joinMap.put(fjj[0].trim(), fjj[1].trim());
                        }
                    }
                }
            }
        }
        if (joinMap != null && !joinMap.isEmpty() && join.length() > 0) {
            String jj = join.toString();
            for (Entry<String, String> e : joinMap.entrySet()) {
                String tmp = "inner join " + e.getKey();
                int k = jj.indexOf(tmp);
                if (k >= 0) {
                    String ss = join.substring(k + tmp.length()).trim();
                    int m = ss.indexOf(" ");
                    if (m > 0) {
                        ss = ss.substring(0, m);
                    }
                    jj = jj.replace(ss, e.getValue());
                    /*lastJoinPrefix = lastJoinPrefix.replaceAll(ss, e.getValue());
                    join.replace(k, k + tmp.length() + 1 + ss.length(), "");*/
                }
            }
        }
        if (select.length() == 0) {
            select.append("select ").append(lastJoinPrefix).append(childAttribute).append(" from ")
                    .append(rootClassName).append(" o ");
        }
        if (join.length() > 0) {
            select.append(join);
        }
        if (filter != null && !filter.isEmpty()) {
            if (!filter.toLowerCase().contains("where"))
                select.append(" where ");
            select.append(filter);
        }
        select.append(" order by ").append(lastJoinPrefix).append(childAttribute).append(" asc");
        String jpql = select.toString();
        List<Date> dtParams = new ArrayList<Date>();
        try {
            em = getEntityManager();
            jpql = replaceDateParameters(jpql, dtParams);
            Query q = em.createQuery(jpql);
            List<Object> list = getResults(dtParams, q);
            if (list != null && !list.isEmpty()) {
                Map<String, String> map = new LinkedHashMap<String, String>();
                for (Object o : list) {
                    StorageHelper.fillGetAllMap(map, o);
                }
                return map;
            } else
                return null;
        } catch (Exception e) {
            logger.log(Level.SEVERE, "Exception in getAll " + e.getMessage(), e);
            throw new PersistenceException("Exception in getAll " + e.getMessage(), e);
        } finally {
            closeEntityManager(em);
        }
    } else {
        try {
            em = getEntityManager();
            String jql = "select distinct o.";
            jql += childAttribute + " from " + rootClassName + " o ";
            if (filter != null && !filter.isEmpty()) {
                jql += filter;
            }
            jql += " order by o." + childAttribute + " asc";
            List<Date> dtParams = new ArrayList<Date>();
            jql = replaceDateParameters(jql, dtParams);
            Query q = em.createQuery(jql);
            List<Object> list = getResults(dtParams, q);

            if (list != null && !list.isEmpty()) {
                Map<String, String> map = new LinkedHashMap<String, String>();
                for (Object o : list) {
                    StorageHelper.fillGetAllMap(map, o);
                }
                return map;
            } else
                return null;
        } catch (Exception e) {
            logger.log(Level.SEVERE, "Exception in getAll " + e.getMessage(), e);
            throw new PersistenceException("Exception in getAll " + e.getMessage(), e);
        } finally {
            closeEntityManager(em);
        }
    }
}

From source file:org.dasein.persist.PersistentCache.java

@SuppressWarnings({ "rawtypes", "unchecked" })
protected Object mapValue(String fieldName, Object dataStoreValue, Class<?> toType, ParameterizedType ptype)
        throws PersistenceException {
    LookupDelegate delegate = getLookupDelegate(fieldName);

    if (dataStoreValue != null && delegate != null && !delegate.validate(dataStoreValue.toString())) {
        throw new PersistenceException("Value " + dataStoreValue + " for " + fieldName + " is not valid.");
    }/*from w  w  w  .j  av a2s.c om*/
    try {
        if (toType.equals(String.class)) {
            if (dataStoreValue != null && !(dataStoreValue instanceof String)) {
                dataStoreValue = dataStoreValue.toString();
            }
        } else if (Enum.class.isAssignableFrom(toType)) {
            if (dataStoreValue != null) {
                Enum e = Enum.valueOf((Class<? extends Enum>) toType, dataStoreValue.toString());

                dataStoreValue = e;
            }
        } else if (toType.equals(Boolean.class) || toType.equals(boolean.class)) {
            if (dataStoreValue == null) {
                dataStoreValue = false;
            } else if (!(dataStoreValue instanceof Boolean)) {
                if (Number.class.isAssignableFrom(dataStoreValue.getClass())) {
                    dataStoreValue = (((Number) dataStoreValue).intValue() != 0);
                } else {
                    dataStoreValue = (dataStoreValue.toString().trim().equalsIgnoreCase("true")
                            || dataStoreValue.toString().trim().equalsIgnoreCase("y"));
                }
            }
        } else if (Number.class.isAssignableFrom(toType) || toType.equals(byte.class)
                || toType.equals(short.class) || toType.equals(long.class) || toType.equals(int.class)
                || toType.equals(float.class) || toType.equals(double.class)) {
            if (dataStoreValue == null) {
                if (toType.equals(int.class) || toType.equals(short.class) || toType.equals(long.class)) {
                    dataStoreValue = 0;
                } else if (toType.equals(float.class) || toType.equals(double.class)) {
                    dataStoreValue = 0.0f;
                }
            } else if (toType.equals(Number.class)) {
                if (!(dataStoreValue instanceof Number)) {
                    if (dataStoreValue instanceof String) {
                        try {
                            dataStoreValue = Double.parseDouble((String) dataStoreValue);
                        } catch (NumberFormatException e) {
                            throw new PersistenceException("Unable to map " + fieldName + " as " + toType
                                    + " using " + dataStoreValue);
                        }
                    } else if (dataStoreValue instanceof Boolean) {
                        dataStoreValue = (((Boolean) dataStoreValue) ? 1 : 0);
                    } else {
                        throw new PersistenceException(
                                "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                    }
                }
            } else if (toType.equals(Integer.class) || toType.equals(int.class)) {
                if (dataStoreValue instanceof Number) {
                    if (!(dataStoreValue instanceof Integer)) {
                        dataStoreValue = ((Number) dataStoreValue).intValue();
                    }
                } else if (dataStoreValue instanceof String) {
                    try {
                        dataStoreValue = Integer.parseInt((String) dataStoreValue);
                    } catch (NumberFormatException e) {
                        throw new PersistenceException(
                                "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                    }
                } else if (dataStoreValue instanceof Boolean) {
                    dataStoreValue = (((Boolean) dataStoreValue) ? 1 : 0);
                } else {
                    throw new PersistenceException(
                            "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                }
            } else if (toType.equals(Long.class) || toType.equals(long.class)) {
                if (dataStoreValue instanceof Number) {
                    if (!(dataStoreValue instanceof Long)) {
                        dataStoreValue = ((Number) dataStoreValue).longValue();
                    }
                } else if (dataStoreValue instanceof String) {
                    try {
                        dataStoreValue = Long.parseLong((String) dataStoreValue);
                    } catch (NumberFormatException e) {
                        throw new PersistenceException(
                                "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                    }
                } else if (dataStoreValue instanceof Boolean) {
                    dataStoreValue = (((Boolean) dataStoreValue) ? 1L : 0L);
                } else {
                    throw new PersistenceException(
                            "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                }
            } else if (toType.equals(Byte.class) || toType.equals(byte.class)) {
                if (dataStoreValue instanceof Number) {
                    if (!(dataStoreValue instanceof Byte)) {
                        dataStoreValue = ((Number) dataStoreValue).byteValue();
                    }
                } else if (dataStoreValue instanceof String) {
                    try {
                        dataStoreValue = Byte.parseByte((String) dataStoreValue);
                    } catch (NumberFormatException e) {
                        throw new PersistenceException(
                                "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                    }
                } else if (dataStoreValue instanceof Boolean) {
                    dataStoreValue = (((Boolean) dataStoreValue) ? 1 : 0);
                } else {
                    throw new PersistenceException(
                            "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                }
            } else if (toType.equals(Short.class) || toType.equals(short.class)) {
                if (dataStoreValue instanceof Number) {
                    if (!(dataStoreValue instanceof Short)) {
                        dataStoreValue = ((Number) dataStoreValue).shortValue();
                    }
                } else if (dataStoreValue instanceof String) {
                    try {
                        dataStoreValue = Short.parseShort((String) dataStoreValue);
                    } catch (NumberFormatException e) {
                        throw new PersistenceException(
                                "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                    }
                } else if (dataStoreValue instanceof Boolean) {
                    dataStoreValue = (((Boolean) dataStoreValue) ? 1 : 0);
                } else {
                    throw new PersistenceException(
                            "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                }
            } else if (toType.equals(Double.class) || toType.equals(double.class)) {
                if (dataStoreValue instanceof Number) {
                    if (!(dataStoreValue instanceof Double)) {
                        dataStoreValue = ((Number) dataStoreValue).doubleValue();
                    }
                } else if (dataStoreValue instanceof String) {
                    try {
                        dataStoreValue = Double.parseDouble((String) dataStoreValue);
                    } catch (NumberFormatException e) {
                        throw new PersistenceException(
                                "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                    }
                } else if (dataStoreValue instanceof Boolean) {
                    dataStoreValue = (((Boolean) dataStoreValue) ? 1.0 : 0.0);
                } else {
                    throw new PersistenceException(
                            "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                }
            } else if (toType.equals(Float.class) || toType.equals(float.class)) {
                if (dataStoreValue instanceof Number) {
                    if (!(dataStoreValue instanceof Float)) {
                        dataStoreValue = ((Number) dataStoreValue).floatValue();
                    }
                } else if (dataStoreValue instanceof String) {
                    try {
                        dataStoreValue = Float.parseFloat((String) dataStoreValue);
                    } catch (NumberFormatException e) {
                        throw new PersistenceException(
                                "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                    }
                } else if (dataStoreValue instanceof Boolean) {
                    dataStoreValue = (((Boolean) dataStoreValue) ? 1.0f : 0.0f);
                } else {
                    throw new PersistenceException(
                            "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                }
            } else if (toType.equals(BigDecimal.class)) {
                if (dataStoreValue instanceof Number) {
                    if (!(dataStoreValue instanceof BigDecimal)) {
                        if (dataStoreValue instanceof BigInteger) {
                            dataStoreValue = new BigDecimal((BigInteger) dataStoreValue);
                        } else {
                            dataStoreValue = BigDecimal.valueOf(((Number) dataStoreValue).doubleValue());
                        }
                    }
                } else if (dataStoreValue instanceof String) {
                    try {
                        dataStoreValue = new BigDecimal((String) dataStoreValue);
                    } catch (NumberFormatException e) {
                        throw new PersistenceException(
                                "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                    }
                } else if (dataStoreValue instanceof Boolean) {
                    dataStoreValue = new BigDecimal((((Boolean) dataStoreValue) ? 1.0 : 0.0));
                } else {
                    throw new PersistenceException(
                            "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                }
            } else if (toType.equals(BigInteger.class)) {
                if (dataStoreValue instanceof Number) {
                    if (!(dataStoreValue instanceof BigInteger)) {
                        if (dataStoreValue instanceof BigDecimal) {
                            dataStoreValue = ((BigDecimal) dataStoreValue).toBigInteger();
                        } else {
                            dataStoreValue = BigInteger.valueOf(((Number) dataStoreValue).longValue());
                        }
                    }
                } else if (dataStoreValue instanceof String) {
                    try {
                        dataStoreValue = new BigDecimal((String) dataStoreValue);
                    } catch (NumberFormatException e) {
                        throw new PersistenceException(
                                "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                    }
                } else if (dataStoreValue instanceof Boolean) {
                    dataStoreValue = new BigDecimal((((Boolean) dataStoreValue) ? 1.0 : 0.0));
                } else {
                    throw new PersistenceException(
                            "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                }
            } else if (dataStoreValue != null) {
                logger.error("Type of dataStoreValue=" + dataStoreValue.getClass());
                throw new PersistenceException(
                        "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
            }
        } else if (toType.equals(Locale.class)) {
            if (dataStoreValue != null && !(dataStoreValue instanceof Locale)) {
                String[] parts = dataStoreValue.toString().split("_");

                if (parts != null && parts.length > 1) {
                    dataStoreValue = new Locale(parts[0], parts[1]);
                } else {
                    dataStoreValue = new Locale(parts[0]);
                }
            }
        } else if (Measured.class.isAssignableFrom(toType)) {
            if (dataStoreValue != null && ptype != null) {
                if (Number.class.isAssignableFrom(dataStoreValue.getClass())) {
                    Constructor<? extends Measured> constructor = null;
                    double value = ((Number) dataStoreValue).doubleValue();

                    for (Constructor<?> c : toType.getDeclaredConstructors()) {
                        Class[] args = c.getParameterTypes();

                        if (args != null && args.length == 2 && Number.class.isAssignableFrom(args[0])
                                && UnitOfMeasure.class.isAssignableFrom(args[1])) {
                            constructor = (Constructor<? extends Measured>) c;
                            break;
                        }
                    }
                    if (constructor == null) {
                        throw new PersistenceException("Unable to map with no proper constructor");
                    }
                    dataStoreValue = constructor.newInstance(value,
                            ((Class<?>) ptype.getActualTypeArguments()[0]).newInstance());
                } else if (!(dataStoreValue instanceof Measured)) {
                    try {
                        dataStoreValue = Double.parseDouble(dataStoreValue.toString());
                    } catch (NumberFormatException e) {
                        Method method = null;

                        for (Method m : toType.getDeclaredMethods()) {
                            if (Modifier.isStatic(m.getModifiers()) && m.getName().equals("valueOf")) {
                                if (m.getParameterTypes().length == 1
                                        && m.getParameterTypes()[0].equals(String.class)) {
                                    method = m;
                                    break;
                                }
                            }
                        }
                        if (method == null) {
                            throw new PersistenceException("Don't know how to map " + dataStoreValue + " to "
                                    + toType + "<" + ptype + ">");
                        }
                        dataStoreValue = method.invoke(null, dataStoreValue.toString());
                    }
                }
                // just because we converted it to a measured object above doesn't mean
                // we have the unit of measure right
                if (dataStoreValue instanceof Measured) {
                    UnitOfMeasure targetUom = (UnitOfMeasure) ((Class<?>) ptype.getActualTypeArguments()[0])
                            .newInstance();

                    if (!(((Measured) dataStoreValue).getUnitOfMeasure()).equals(targetUom)) {
                        dataStoreValue = ((Measured) dataStoreValue).convertTo(
                                (UnitOfMeasure) ((Class<?>) ptype.getActualTypeArguments()[0]).newInstance());
                    }
                }
            }
        } else if (toType.equals(UUID.class)) {
            if (dataStoreValue != null && !(dataStoreValue instanceof UUID)) {
                dataStoreValue = UUID.fromString(dataStoreValue.toString());
            }
        } else if (toType.equals(TimeZone.class)) {
            if (dataStoreValue != null && !(dataStoreValue instanceof TimeZone)) {
                dataStoreValue = TimeZone.getTimeZone(dataStoreValue.toString());
            }
        } else if (toType.equals(Currency.class)) {
            if (dataStoreValue != null && !(dataStoreValue instanceof Currency)) {
                dataStoreValue = Currency.getInstance(dataStoreValue.toString());
            }
        } else if (toType.isArray()) {
            Class<?> t = toType.getComponentType();

            if (dataStoreValue == null) {
                dataStoreValue = Array.newInstance(t, 0);
            } else if (dataStoreValue instanceof JSONArray) {
                JSONArray arr = (JSONArray) dataStoreValue;

                if (long.class.isAssignableFrom(t)) {
                    long[] replacement = (long[]) Array.newInstance(long.class, arr.length());

                    for (int i = 0; i < arr.length(); i++) {
                        replacement[i] = (Long) mapValue(fieldName, arr.get(i), t, null);
                    }
                    dataStoreValue = replacement;
                } else if (int.class.isAssignableFrom(t)) {
                    int[] replacement = (int[]) Array.newInstance(int.class, arr.length());

                    for (int i = 0; i < arr.length(); i++) {
                        replacement[i] = (Integer) mapValue(fieldName, arr.get(i), t, null);
                    }
                    dataStoreValue = replacement;
                } else if (float.class.isAssignableFrom(t)) {
                    float[] replacement = (float[]) Array.newInstance(float.class, arr.length());

                    for (int i = 0; i < arr.length(); i++) {
                        replacement[i] = (Float) mapValue(fieldName, arr.get(i), t, null);
                    }
                    dataStoreValue = replacement;
                } else if (double.class.isAssignableFrom(t)) {
                    double[] replacement = (double[]) Array.newInstance(double.class, arr.length());

                    for (int i = 0; i < arr.length(); i++) {
                        replacement[i] = (Double) mapValue(fieldName, arr.get(i), t, null);
                    }
                    dataStoreValue = replacement;
                } else if (boolean.class.isAssignableFrom(t)) {
                    boolean[] replacement = (boolean[]) Array.newInstance(boolean.class, arr.length());

                    for (int i = 0; i < arr.length(); i++) {
                        replacement[i] = (Boolean) mapValue(fieldName, arr.get(i), t, null);
                    }
                    dataStoreValue = replacement;
                } else {
                    Object[] replacement = (Object[]) Array.newInstance(t, arr.length());

                    for (int i = 0; i < arr.length(); i++) {
                        replacement[i] = mapValue(fieldName, arr.get(i), t, null);
                    }
                    dataStoreValue = replacement;
                }
            } else if (!dataStoreValue.getClass().isArray()) {
                logger.error("Unable to map data store type " + dataStoreValue.getClass().getName() + " to "
                        + toType.getName());
                logger.error("Value of " + fieldName + "=" + dataStoreValue);
                throw new PersistenceException("Data store type=" + dataStoreValue.getClass().getName());
            }
        } else if (dataStoreValue != null && !toType.isAssignableFrom(dataStoreValue.getClass())) {
            Annotation[] alist = toType.getDeclaredAnnotations();
            boolean autoJSON = false;

            for (Annotation a : alist) {
                if (a instanceof AutoJSON) {
                    autoJSON = true;
                }
            }
            if (autoJSON) {
                dataStoreValue = autoDeJSON(toType, (JSONObject) dataStoreValue);
            } else {
                try {
                    Method m = toType.getDeclaredMethod("valueOf", JSONObject.class);

                    dataStoreValue = m.invoke(null, dataStoreValue);
                } catch (NoSuchMethodException ignore) {
                    try {
                        Method m = toType.getDeclaredMethod("valueOf", String.class);

                        if (m != null) {
                            dataStoreValue = m.invoke(null, dataStoreValue.toString());
                        } else {
                            throw new PersistenceException(
                                    "No valueOf() field in " + toType + " for mapping " + fieldName);
                        }
                    } catch (NoSuchMethodException e) {
                        throw new PersistenceException("No valueOf() field in " + toType + " for mapping "
                                + fieldName + " with " + dataStoreValue + ": ("
                                + dataStoreValue.getClass().getName() + " vs " + toType.getName() + ")");
                    }
                }
            }
        }
    } catch (Exception e) {
        String err = "Error mapping field in " + toType + " for " + fieldName + ": " + e.getMessage();
        logger.error(err, e);
        throw new PersistenceException();
    }
    return dataStoreValue;
}

From source file:com.clark.func.Functions.java

/**
 * <p>//from  www.  j a v a2 s .  c o  m
 * </p>
 * 
 * @param cls
 * @param parameterizedType
 * @param typeVarAssigns
 */
private static <T> void mapTypeVariablesToArguments(Class<T> cls, ParameterizedType parameterizedType,
        Map<TypeVariable<?>, Type> typeVarAssigns) {
    // capture the type variables from the owner type that have assignments
    Type ownerType = parameterizedType.getOwnerType();

    if (ownerType instanceof ParameterizedType) {
        // recursion to make sure the owner's owner type gets processed
        mapTypeVariablesToArguments(cls, (ParameterizedType) ownerType, typeVarAssigns);
    }

    // parameterizedType is a generic interface/class (or it's in the owner
    // hierarchy of said interface/class) implemented/extended by the class
    // cls. Find out which type variables of cls are type arguments of
    // parameterizedType:
    Type[] typeArgs = parameterizedType.getActualTypeArguments();

    // of the cls's type variables that are arguments of parameterizedType,
    // find out which ones can be determined from the super type's arguments
    TypeVariable<?>[] typeVars = getRawType(parameterizedType).getTypeParameters();

    // use List view of type parameters of cls so the contains() method can
    // be used:
    List<TypeVariable<Class<T>>> typeVarList = Arrays.asList(cls.getTypeParameters());

    for (int i = 0; i < typeArgs.length; i++) {
        TypeVariable<?> typeVar = typeVars[i];
        Type typeArg = typeArgs[i];

        // argument of parameterizedType is a type variable of cls
        if (typeVarList.contains(typeArg)
                // type variable of parameterizedType has an assignment in
                // the super type.
                && typeVarAssigns.containsKey(typeVar)) {
            // map the assignment to the cls's type variable
            typeVarAssigns.put((TypeVariable<?>) typeArg, typeVarAssigns.get(typeVar));
        }
    }
}

From source file:com.clark.func.Functions.java

/**
 * <p>/*from   ww w  .  j  av a  2s. c  o m*/
 * </p>
 * 
 * @param parameterizedType
 * @param toClass
 * @param subtypeVarAssigns
 * @return
 */
private static Map<TypeVariable<?>, Type> getTypeArguments(ParameterizedType parameterizedType,
        Class<?> toClass, Map<TypeVariable<?>, Type> subtypeVarAssigns) {
    Class<?> cls = getRawType(parameterizedType);

    // make sure they're assignable
    if (!isAssignable(cls, toClass)) {
        return null;
    }

    Type ownerType = parameterizedType.getOwnerType();
    Map<TypeVariable<?>, Type> typeVarAssigns;

    if (ownerType instanceof ParameterizedType) {
        // get the owner type arguments first
        ParameterizedType parameterizedOwnerType = (ParameterizedType) ownerType;
        typeVarAssigns = getTypeArguments(parameterizedOwnerType, getRawType(parameterizedOwnerType),
                subtypeVarAssigns);
    } else {
        // no owner, prep the type variable assignments map
        typeVarAssigns = subtypeVarAssigns == null ? new HashMap<TypeVariable<?>, Type>()
                : new HashMap<TypeVariable<?>, Type>(subtypeVarAssigns);
    }

    // get the subject parameterized type's arguments
    Type[] typeArgs = parameterizedType.getActualTypeArguments();
    // and get the corresponding type variables from the raw class
    TypeVariable<?>[] typeParams = cls.getTypeParameters();

    // map the arguments to their respective type variables
    for (int i = 0; i < typeParams.length; i++) {
        Type typeArg = typeArgs[i];
        typeVarAssigns.put(typeParams[i],
                typeVarAssigns.containsKey(typeArg) ? typeVarAssigns.get(typeArg) : typeArg);
    }

    if (toClass.equals(cls)) {
        // target class has been reached. Done.
        return typeVarAssigns;
    }

    // walk the inheritance hierarchy until the target class is reached
    return getTypeArguments(getClosestParentType(cls, toClass), toClass, typeVarAssigns);
}