问:
Using a generic type of any nested subclass within its abstract superclass
Suppose you have the following abstract java class:

```<code>public abstract class AbstractRequestHandler<I,O> {
    I input;
    O output;
}
</code>```

and the following child classes hierarchy:

```<code>public abstract class AbstractUserRequestHandler<I extends User,O> extends AbstractRequestHandler<I,O>{...}
public abstract class AbstractUniversityRequestHandler<I extends UniversityUser> extends AbstractUserRequestHandler<I,String>{...}
public class StudentRequestHandler extends AbstractUniversityRequestHandler<Student>{...}
public class TeacherRequestHandler extends AbstractUniversityRequestHandler<Teacher>{...}
</code>```

Suppose you need to use at a given point on the super class the generic type, for example in order to deserialize on the constructor the request json to the specific request object using gson library as follow:

```<code>public AbstractRequestHandler(final String inputJson) {
        input = new Gson().fromJson(inputJson,typeOfI);
}
</code>```

You need the type of generic I within variable "typeOfI"

Is there a global solution that allows to get the generic type specified by a concrete child class that respects the following constraints?

The type is gotten at runtime regardless the child classes hierarchy ( that can be also more complex the one given as example on this question )

The developer just needs to define the generic extending the super class without manually specify the generic type somewhere on concrete child class ( for example on overrided method or constructor )

So that if you want to define a new concrete child that assign a new value to a generic you can just write the following concrete class for example:

```<code>public class StudentRequestHandler extends AbstractUniversityRequestHandler<Student>{

    public StudentRequestHandler(String inputJson) {
        super(inputJson);
    }

}
</code>```

I found the following solutions but they don't respect both the asked solution constraints.

Solution that breaks constraint n°2

A solution could be to define an abstract method on the superclass as follow

```<code>protected abstract Type getRequestType();
</code>```

and then implement it on every concrete child class that defines the generic:

```<code>public class StudentRequestHandler extends AbstractUniversityRequestHandler<Student>{

    public StudentRequestHandler(String inputJson) {
        super(inputJson);
    }

    @Override
    protected Type getRequestType() {
        return Student.class;
    }
}
</code>```

Then the getRequestType() method can be used on constructor on the target superclass:

```<code>public AbstractRequestHandler(final String inputJson) {
        request = new Gson().fromJson(inputJson,getRequestType());
}
</code>```

But even if it works regardless the child classes hierarchy ( respect constraint n°1 ) the developer should manually implement an abstract method on each concrete child class.

Solution that breaks constraint n°1

If the hierarchy is simple having only a direct child that extend from the target superclass, as for example:

```<code>public class TeacherRequestHandler extends AbstractRequestHandler<Teacher,String>{...}
</code>```

a working solution has been proposed by @naikus ( https://stackoverflow.com/users/306602/naikus ) on the following stackoverflow thread:
Using a generic type of a subclass within it's abstract superclass?

However this doesn't work if the concrete class is not a direct child of the superclass that defines the generics ( as the one proposed as example on this question ).

答:
Edit: after reading your answer and testing many other possible cases I decided to edit your code and re-write it to support all other possible edge cases to include tracking of generics nested deeply inside other generic types.

Sadly to support all cases we need a lot more code than you provided, generics are very tricky, like consider class like this:

```<code>private class SomeClass<A, B, C, D, E, F> {}

private class SomeConfusingClass<A> extends SomeClass<List<Void>[], List<? extends A>[], List<? extends A[][][]>[][][], List<? extends String[]>[], Map<List<? extends A[]>, A[][]>[], A> {}

private class TestClass extends SomeConfusingClass<Void> {}
</code>```

To even start doing this we need to have own implementation of java generic types to later be able to construct types like List<String>[] as there is no way to create such type dynamically with raw java API.

This is pretty popular way of handling generic in libraries like that, you can see similar thing in jackson library and many more.

So we need implementation of GenericArrayType, ParameterizedType and WildcardType:

```<code>private static class ResolvedGenericArrayType implements GenericArrayType {
    private final Type genericComponentType;

    ResolvedGenericArrayType(Type genericComponentType) {
        this.genericComponentType = genericComponentType;
    }

    @Override
    public Type getGenericComponentType() {
        return genericComponentType;
    }

    public String toString() {
        return getGenericComponentType().toString() + "[]";
    }

    @Override
    public boolean equals(Object o) {
        if (o instanceof GenericArrayType) {
            GenericArrayType that = (GenericArrayType) o;
            return Objects.equals(genericComponentType, that.getGenericComponentType());
        } else
            return false;
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(genericComponentType);
    }
}

private static class ResolvedParameterizedType implements ParameterizedType {
    private final Type[] actualTypeArguments;
    private final Class<?> rawType;
    private final Type ownerType;

    private ResolvedParameterizedType(Type rawType, Type[] actualTypeArguments, Type ownerType) {
        this.actualTypeArguments = actualTypeArguments;
        this.rawType = (Class<?>) rawType;
        this.ownerType = (ownerType != null) ? ownerType : this.rawType.getDeclaringClass();
    }

    public Type[] getActualTypeArguments() {
        return actualTypeArguments.clone();
    }

    public Class<?> getRawType() {
        return rawType;
    }

    public Type getOwnerType() {
        return ownerType;
    }

    @Override
    public boolean equals(Object o) {
        if (!(o instanceof ParameterizedType)) {
            return false;
        }
        ParameterizedType that = (ParameterizedType) o;
        if (this == that)
            return true;
        Type thatOwner = that.getOwnerType();
        Type thatRawType = that.getRawType();
        return Objects.equals(ownerType, thatOwner) && Objects.equals(rawType, thatRawType) &&
                Arrays.equals(actualTypeArguments, that.getActualTypeArguments());
    }

    @Override
    public int hashCode() {
        return Arrays.hashCode(actualTypeArguments) ^
                Objects.hashCode(ownerType) ^
                Objects.hashCode(rawType);
    }

    public String toString() {
        StringBuilder sb = new StringBuilder();
        if (ownerType != null) {
            sb.append(ownerType.getTypeName());
            sb.append("$");
            if (ownerType instanceof ResolvedParameterizedType) {
                sb.append(rawType.getName().replace(((ResolvedParameterizedType) ownerType).rawType.getName() + "$", ""));
            } else
                sb.append(rawType.getSimpleName());
        } else
            sb.append(rawType.getName());
        if (actualTypeArguments != null) {
            StringJoiner sj = new StringJoiner(", ", "<", ">");
            sj.setEmptyValue("");
            for (Type t : actualTypeArguments) {
                sj.add(t.getTypeName());
            }
            sb.append(sj.toString());
        }
        return sb.toString();
    }
}

private static class ResolvedWildcardType implements WildcardType {
    private final Type[] upperBounds;
    private final Type[] lowerBounds;

    public ResolvedWildcardType(Type[] upperBounds, Type[] lowerBounds) {
        this.upperBounds = upperBounds;
        this.lowerBounds = lowerBounds;
    }

    public Type[] getUpperBounds() {
        return upperBounds.clone();
    }

    public Type[] getLowerBounds() {
        return lowerBounds.clone();
    }

    public String toString() {
        Type[] lowerBounds = getLowerBounds();
        Type[] bounds = lowerBounds;
        StringBuilder sb = new StringBuilder();
        if (lowerBounds.length > 0)
            sb.append("? super ");
        else {
            Type[] upperBounds = getUpperBounds();
            if (upperBounds.length > 0 && !upperBounds[0].equals(Object.class)) {
                bounds = upperBounds;
                sb.append("? extends ");
            } else
                return "?";
        }
        StringJoiner sj = new StringJoiner(" & ");
        for (Type bound : bounds) {
            sj.add(bound.getTypeName());
        }
        sb.append(sj.toString());
        return sb.toString();
    }

    @Override
    public boolean equals(Object o) {
        if (o instanceof WildcardType) {
            WildcardType that = (WildcardType) o;
            return Arrays.equals(this.getLowerBounds(), that.getLowerBounds()) && Arrays.equals(this.getUpperBounds(), that.getUpperBounds());
        } else
            return false;
    }

    @Override
    public int hashCode() {
        Type[] lowerBounds = getLowerBounds();
        Type[] upperBounds = getUpperBounds();
        return Arrays.hashCode(lowerBounds) ^ Arrays.hashCode(upperBounds);
    }
}
</code>```

You can basically copy them from JDK and just do some cleanup.

Next utility we need is a function to validate at the end if we did everything right, like we don't want to return Map<List<? extends X>[]> where X is still not resolved TypeVariable:

```<code>private static boolean isDefined(Type type) {
    if (type instanceof Class) {
        return true;
    }
    if (type instanceof GenericArrayType) {
        return isDefined(((GenericArrayType) type).getGenericComponentType());
    }
    if (type instanceof WildcardType) {
        for (Type lowerBound : ((WildcardType) type).getLowerBounds()) {
            if (!isDefined(lowerBound)) {
                return false;
            }
        }
        for (Type upperBound : ((WildcardType) type).getUpperBounds()) {
            if (!isDefined(upperBound)) {
                return false;
            }
        }
        return true;
    }
    if (!(type instanceof ParameterizedType)) {
        return false;
    }
    for (Type typeArgument : ((ParameterizedType) type).getActualTypeArguments()) {
        if (!isDefined(typeArgument)) {
            return false;
        }
    }
    return true;
}
</code>```

Simple recursive function will do this for us. We just check for every possible generic type and check if every member of it is also defined, and unless we will find some hidden TypeVariable we are fine.

Main function can stay the same as in your code, we only will edit that one check at the end to use our new function:

```<code>public static Type getParameterizedType(Class<?> klass, Class<?> rootClass, int paramTypeNumber) throws GenericsException {

    int targetClassParametersNumber = rootClass.getTypeParameters().length;
    if (targetClassParametersNumber == 0) {
        throw new GenericsException(String.format("Target class [%s] has no parameters type", rootClass.getName()));
    } else if (targetClassParametersNumber - 1 < paramTypeNumber)
        throw new GenericsException(String.format("Target class [%s] has parameters type which index start from [0] to [%s]. You requested instead parameter with index [%s]", rootClass, paramTypeNumber - 1, targetClassParametersNumber));

    Type type = analyzeParameterizedTypes(klass, klass, rootClass, paramTypeNumber, null);
    if (!isDefined(type))
        throw new GenericsException(String.format("Parameter [%s] with index [%d] defined on class [%s] has not been valued yet on child class [%s]", type, paramTypeNumber, rootClass.getName(), klass.getName()));
    return type;
}
</code>```

Now lets work on our main

```<code>public static Type analyzeParameterizedTypes(final Class<?> klass, final Class<?> targetClass, final Class<?> rootClass, final int paramTypeNumber, Map<Integer, Type> childClassTypes) throws GenericsException {
</code>```

function, the begging stays the same, we collect all TypeVariable to simple map, keeping already collected information from previous loop on previous class.

```<code>    Type superclassType = klass.getGenericSuperclass();
    Map<TypeVariable<?>, Type> currentClassTypes = new HashMap<>();
    int z = 0;
    if (childClassTypes != null) {
        for (TypeVariable<?> variable : klass.getTypeParameters()) {
            currentClassTypes.put(variable, childClassTypes.get(z));
            z++;
        }
    }
</code>```

Then we have our loop collecting and refining our type arguments:

```<code>    Map<Integer, Type> superClassesTypes = new HashMap<>();
    if (superclassType instanceof ParameterizedType) {
        int i = 0;
        for (final Type argType : ((ParameterizedType) superclassType).getActualTypeArguments()) {
            if (argType instanceof TypeVariable) {
                superClassesTypes.put(i, currentClassTypes.containsKey(argType) ? currentClassTypes.get(argType) : argType);
            } else {
                superClassesTypes.put(i, refineType(klass, argType, currentClassTypesByName));
            }
            i++;
        }
    }
</code>```

There 2 paths for each type argument, if its TypeVariable we just keep tracking it, and if its anything else we try to "refine" it from any possible references to TypeVariable. This is the most complicated process of this code, and this is why we needed all these classes above.

We start from this simple recursive dispatch method that handles all possible types:

```<code>private static Type refineType(Type type, Map<TypeVariable<?>, Type> typeVariablesMap) throws GenericsException {
    if (type instanceof Class) {
        return type;
    }
    if (type instanceof GenericArrayType) {
        return refineArrayType((GenericArrayType) type, typeVariablesMap);
    }
    if (type instanceof ParameterizedType) {
        return refineParameterizedType((ParameterizedType) type, typeVariablesMap);
    }
    if (type instanceof WildcardType) {
        return refineWildcardType((WildcardType) type, typeVariablesMap);
    }
    if (type instanceof TypeVariable) {
        return typeVariablesMap.get(type);
    }
    throw new GenericsException("Unsolvable generic type: " + type);
}
</code>```

And small utility method to run it on array of types:

```<code>private static Type[] refineTypes(Type[] types, Map<TypeVariable<?>, Type> typeVariablesMap) throws GenericsException {
    Type[] refinedTypes = new Type[types.length];
    for (int i = 0; i < types.length; i++) {
        refinedTypes[i] = refineType(types[i], typeVariablesMap);
    }
    return refinedTypes;
}
</code>```

Each type goes to own function, or if its TypeVariable we just fetch resolved one from map. Note that this can return null, and I did not handle it here. This could be improved later. For classes we don't need to do anything so we can just return class itself.

For GenericArrayType we need to first find out how many dimension such array might have (this could be handled by recursion in our refine method too, but then its a bit harder to debug in my opinion):

```<code>private static int getArrayDimensions(GenericArrayType genericArrayType) {
    int levels = 1;
    GenericArrayType currentArrayLevel = genericArrayType;
    while (currentArrayLevel.getGenericComponentType() instanceof GenericArrayType) {
        currentArrayLevel = (GenericArrayType) currentArrayLevel.getGenericComponentType();
        levels += 1;
    }
    return levels;
}
</code>```

Then we want to extract that nested component type of array, so for List[][][] we want just List:

```<code>private static class ResolvedGenericArrayType implements GenericArrayType {
    private final Type genericComponentType;

    ResolvedGenericArrayType(Type genericComponentType) {
        this.genericComponentType = genericComponentType;
    }

    @Override
    public Type getGenericComponentType() {
        return genericComponentType;
    }

    public String toString() {
        return getGenericComponentType().toString() + "[]";
    }

    @Override
    public boolean equals(Object o) {
        if (o instanceof GenericArrayType) {
            GenericArrayType that = (GenericArrayType) o;
            return Objects.equals(genericComponentType, that.getGenericComponentType());
        } else
            return false;
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(genericComponentType);
    }
}

private static class ResolvedParameterizedType implements ParameterizedType {
    private final Type[] actualTypeArguments;
    private final Class<?> rawType;
    private final Type ownerType;

    private ResolvedParameterizedType(Type rawType, Type[] actualTypeArguments, Type ownerType) {
        this.actualTypeArguments = actualTypeArguments;
        this.rawType = (Class<?>) rawType;
        this.ownerType = (ownerType != null) ? ownerType : this.rawType.getDeclaringClass();
    }

    public Type[] getActualTypeArguments() {
        return actualTypeArguments.clone();
    }

    public Class<?> getRawType() {
        return rawType;
    }

    public Type getOwnerType() {
        return ownerType;
    }

    @Override
    public boolean equals(Object o) {
        if (!(o instanceof ParameterizedType)) {
            return false;
        }
        ParameterizedType that = (ParameterizedType) o;
        if (this == that)
            return true;
        Type thatOwner = that.getOwnerType();
        Type thatRawType = that.getRawType();
        return Objects.equals(ownerType, thatOwner) && Objects.equals(rawType, thatRawType) &&
                Arrays.equals(actualTypeArguments, that.getActualTypeArguments());
    }

    @Override
    public int hashCode() {
        return Arrays.hashCode(actualTypeArguments) ^
                Objects.hashCode(ownerType) ^
                Objects.hashCode(rawType);
    }

    public String toString() {
        StringBuilder sb = new StringBuilder();
        if (ownerType != null) {
            sb.append(ownerType.getTypeName());
            sb.append("$");
            if (ownerType instanceof ResolvedParameterizedType) {
                sb.append(rawType.getName().replace(((ResolvedParameterizedType) ownerType).rawType.getName() + "$", ""));
            } else
                sb.append(rawType.getSimpleName());
        } else
            sb.append(rawType.getName());
        if (actualTypeArguments != null) {
            StringJoiner sj = new StringJoiner(", ", "<", ">");
            sj.setEmptyValue("");
            for (Type t : actualTypeArguments) {
                sj.add(t.getTypeName());
            }
            sb.append(sj.toString());
        }
        return sb.toString();
    }
}

private static class ResolvedWildcardType implements WildcardType {
    private final Type[] upperBounds;
    private final Type[] lowerBounds;

    public ResolvedWildcardType(Type[] upperBounds, Type[] lowerBounds) {
        this.upperBounds = upperBounds;
        this.lowerBounds = lowerBounds;
    }

    public Type[] getUpperBounds() {
        return upperBounds.clone();
    }

    public Type[] getLowerBounds() {
        return lowerBounds.clone();
    }

    public String toString() {
        Type[] lowerBounds = getLowerBounds();
        Type[] bounds = lowerBounds;
        StringBuilder sb = new StringBuilder();
        if (lowerBounds.length > 0)
            sb.append("? super ");
        else {
            Type[] upperBounds = getUpperBounds();
            if (upperBounds.length > 0 && !upperBounds[0].equals(Object.class)) {
                bounds = upperBounds;
                sb.append("? extends ");
            } else
                return "?";
        }
        StringJoiner sj = new StringJoiner(" & ");
        for (Type bound : bounds) {
            sj.add(bound.getTypeName());
        }
        sb.append(sj.toString());
        return sb.toString();
    }

    @Override
    public boolean equals(Object o) {
        if (o instanceof WildcardType) {
            WildcardType that = (WildcardType) o;
            return Arrays.equals(this.getLowerBounds(), that.getLowerBounds()) && Arrays.equals(this.getUpperBounds(), that.getUpperBounds());
        } else
            return false;
    }

    @Override
    public int hashCode() {
        Type[] lowerBounds = getLowerBounds();
        Type[] upperBounds = getUpperBounds();
        return Arrays.hashCode(lowerBounds) ^ Arrays.hashCode(upperBounds);
    }
}
</code>```0

And then we need to refine this type, so our List will change to eg List<String>:

```<code>private static class ResolvedGenericArrayType implements GenericArrayType {
    private final Type genericComponentType;

    ResolvedGenericArrayType(Type genericComponentType) {
        this.genericComponentType = genericComponentType;
    }

    @Override
    public Type getGenericComponentType() {
        return genericComponentType;
    }

    public String toString() {
        return getGenericComponentType().toString() + "[]";
    }

    @Override
    public boolean equals(Object o) {
        if (o instanceof GenericArrayType) {
            GenericArrayType that = (GenericArrayType) o;
            return Objects.equals(genericComponentType, that.getGenericComponentType());
        } else
            return false;
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(genericComponentType);
    }
}

private static class ResolvedParameterizedType implements ParameterizedType {
    private final Type[] actualTypeArguments;
    private final Class<?> rawType;
    private final Type ownerType;

    private ResolvedParameterizedType(Type rawType, Type[] actualTypeArguments, Type ownerType) {
        this.actualTypeArguments = actualTypeArguments;
        this.rawType = (Class<?>) rawType;
        this.ownerType = (ownerType != null) ? ownerType : this.rawType.getDeclaringClass();
    }

    public Type[] getActualTypeArguments() {
        return actualTypeArguments.clone();
    }

    public Class<?> getRawType() {
        return rawType;
    }

    public Type getOwnerType() {
        return ownerType;
    }

    @Override
    public boolean equals(Object o) {
        if (!(o instanceof ParameterizedType)) {
            return false;
        }
        ParameterizedType that = (ParameterizedType) o;
        if (this == that)
            return true;
        Type thatOwner = that.getOwnerType();
        Type thatRawType = that.getRawType();
        return Objects.equals(ownerType, thatOwner) && Objects.equals(rawType, thatRawType) &&
                Arrays.equals(actualTypeArguments, that.getActualTypeArguments());
    }

    @Override
    public int hashCode() {
        return Arrays.hashCode(actualTypeArguments) ^
                Objects.hashCode(ownerType) ^
                Objects.hashCode(rawType);
    }

    public String toString() {
        StringBuilder sb = new StringBuilder();
        if (ownerType != null) {
            sb.append(ownerType.getTypeName());
            sb.append("$");
            if (ownerType instanceof ResolvedParameterizedType) {
                sb.append(rawType.getName().replace(((ResolvedParameterizedType) ownerType).rawType.getName() + "$", ""));
            } else
                sb.append(rawType.getSimpleName());
        } else
            sb.append(rawType.getName());
        if (actualTypeArguments != null) {
            StringJoiner sj = new StringJoiner(", ", "<", ">");
            sj.setEmptyValue("");
            for (Type t : actualTypeArguments) {
                sj.add(t.getTypeName());
            }
            sb.append(sj.toString());
        }
        return sb.toString();
    }
}

private static class ResolvedWildcardType implements WildcardType {
    private final Type[] upperBounds;
    private final Type[] lowerBounds;

    public ResolvedWildcardType(Type[] upperBounds, Type[] lowerBounds) {
        this.upperBounds = upperBounds;
        this.lowerBounds = lowerBounds;
    }

    public Type[] getUpperBounds() {
        return upperBounds.clone();
    }

    public Type[] getLowerBounds() {
        return lowerBounds.clone();
    }

    public String toString() {
        Type[] lowerBounds = getLowerBounds();
        Type[] bounds = lowerBounds;
        StringBuilder sb = new StringBuilder();
        if (lowerBounds.length > 0)
            sb.append("? super ");
        else {
            Type[] upperBounds = getUpperBounds();
            if (upperBounds.length > 0 && !upperBounds[0].equals(Object.class)) {
                bounds = upperBounds;
                sb.append("? extends ");
            } else
                return "?";
        }
        StringJoiner sj = new StringJoiner(" & ");
        for (Type bound : bounds) {
            sj.add(bound.getTypeName());
        }
        sb.append(sj.toString());
        return sb.toString();
    }

    @Override
    public boolean equals(Object o) {
        if (o instanceof WildcardType) {
            WildcardType that = (WildcardType) o;
            return Arrays.equals(this.getLowerBounds(), that.getLowerBounds()) && Arrays.equals(this.getUpperBounds(), that.getUpperBounds());
        } else
            return false;
    }

    @Override
    public int hashCode() {
        Type[] lowerBounds = getLowerBounds();
        Type[] upperBounds = getUpperBounds();
        return Arrays.hashCode(lowerBounds) ^ Arrays.hashCode(upperBounds);
    }
}
</code>```1

And rebuild our generic structure using refined type, so our created List<String> will change back to List<String>[][][]:

```<code>private static class ResolvedGenericArrayType implements GenericArrayType {
    private final Type genericComponentType;

    ResolvedGenericArrayType(Type genericComponentType) {
        this.genericComponentType = genericComponentType;
    }

    @Override
    public Type getGenericComponentType() {
        return genericComponentType;
    }

    public String toString() {
        return getGenericComponentType().toString() + "[]";
    }

    @Override
    public boolean equals(Object o) {
        if (o instanceof GenericArrayType) {
            GenericArrayType that = (GenericArrayType) o;
            return Objects.equals(genericComponentType, that.getGenericComponentType());
        } else
            return false;
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(genericComponentType);
    }
}

private static class ResolvedParameterizedType implements ParameterizedType {
    private final Type[] actualTypeArguments;
    private final Class<?> rawType;
    private final Type ownerType;

    private ResolvedParameterizedType(Type rawType, Type[] actualTypeArguments, Type ownerType) {
        this.actualTypeArguments = actualTypeArguments;
        this.rawType = (Class<?>) rawType;
        this.ownerType = (ownerType != null) ? ownerType : this.rawType.getDeclaringClass();
    }

    public Type[] getActualTypeArguments() {
        return actualTypeArguments.clone();
    }

    public Class<?> getRawType() {
        return rawType;
    }

    public Type getOwnerType() {
        return ownerType;
    }

    @Override
    public boolean equals(Object o) {
        if (!(o instanceof ParameterizedType)) {
            return false;
        }
        ParameterizedType that = (ParameterizedType) o;
        if (this == that)
            return true;
        Type thatOwner = that.getOwnerType();
        Type thatRawType = that.getRawType();
        return Objects.equals(ownerType, thatOwner) && Objects.equals(rawType, thatRawType) &&
                Arrays.equals(actualTypeArguments, that.getActualTypeArguments());
    }

    @Override
    public int hashCode() {
        return Arrays.hashCode(actualTypeArguments) ^
                Objects.hashCode(ownerType) ^
                Objects.hashCode(rawType);
    }

    public String toString() {
        StringBuilder sb = new StringBuilder();
        if (ownerType != null) {
            sb.append(ownerType.getTypeName());
            sb.append("$");
            if (ownerType instanceof ResolvedParameterizedType) {
                sb.append(rawType.getName().replace(((ResolvedParameterizedType) ownerType).rawType.getName() + "$", ""));
            } else
                sb.append(rawType.getSimpleName());
        } else
            sb.append(rawType.getName());
        if (actualTypeArguments != null) {
            StringJoiner sj = new StringJoiner(", ", "<", ">");
            sj.setEmptyValue("");
            for (Type t : actualTypeArguments) {
                sj.add(t.getTypeName());
            }
            sb.append(sj.toString());
        }
        return sb.toString();
    }
}

private static class ResolvedWildcardType implements WildcardType {
    private final Type[] upperBounds;
    private final Type[] lowerBounds;

    public ResolvedWildcardType(Type[] upperBounds, Type[] lowerBounds) {
        this.upperBounds = upperBounds;
        this.lowerBounds = lowerBounds;
    }

    public Type[] getUpperBounds() {
        return upperBounds.clone();
    }

    public Type[] getLowerBounds() {
        return lowerBounds.clone();
    }

    public String toString() {
        Type[] lowerBounds = getLowerBounds();
        Type[] bounds = lowerBounds;
        StringBuilder sb = new StringBuilder();
        if (lowerBounds.length > 0)
            sb.append("? super ");
        else {
            Type[] upperBounds = getUpperBounds();
            if (upperBounds.length > 0 && !upperBounds[0].equals(Object.class)) {
                bounds = upperBounds;
                sb.append("? extends ");
            } else
                return "?";
        }
        StringJoiner sj = new StringJoiner(" & ");
        for (Type bound : bounds) {
            sj.add(bound.getTypeName());
        }
        sb.append(sj.toString());
        return sb.toString();
    }

    @Override
    public boolean equals(Object o) {
        if (o instanceof WildcardType) {
            WildcardType that = (WildcardType) o;
            return Arrays.equals(this.getLowerBounds(), that.getLowerBounds()) && Arrays.equals(this.getUpperBounds(), that.getUpperBounds());
        } else
            return false;
    }

    @Override
    public int hashCode() {
        Type[] lowerBounds = getLowerBounds();
        Type[] upperBounds = getUpperBounds();
        return Arrays.hashCode(lowerBounds) ^ Arrays.hashCode(upperBounds);
    }
}
</code>```2

And whole function looks like this:

```<code>private static Type refineArrayType( GenericArrayType genericArrayType, Map<TypeVariable<?>, Type> typeVariablesMap) throws GenericsException {
    int levels = getArrayDimensions(genericArrayType);
    Type arrayComponentType = refineType(getArrayNestedComponentType(genericArrayType), typeVariablesMap);
    return buildArrayType(arrayComponentType, levels);
}
</code>```

For ParameterizedType its much simpler, we just refine type arguments, and create new ParameterizedType instance with these refined arguments:

```<code>private static Type refineParameterizedType(ParameterizedType parameterizedType, Map<TypeVariable<?>, Type> typeVariablesMap) throws GenericsException {
    Type[] refinedTypeArguments = refineTypes(parameterizedType.getActualTypeArguments(), typeVariablesMap);
    return new ResolvedParameterizedType(parameterizedType.getRawType(), refinedTypeArguments, parameterizedType.getOwnerType());
}
</code>```

Same for WildcardType:

```<code>private static Type refineWildcardType(WildcardType wildcardType, Map<TypeVariable<?>, Type> typeVariablesMap) throws GenericsException {
    Type[] refinedUpperBounds = refineTypes(wildcardType.getUpperBounds(), typeVariablesMap);
    Type[] refinedLowerBounds = refineTypes(wildcardType.getLowerBounds(), typeVariablesMap);
    return new ResolvedWildcardType(refinedUpperBounds, refinedLowerBounds);
}
</code>```

And this leaves us with whole analyze function looking like this:

```<code>public static Type analyzeParameterizedTypes(final Class<?> klass, final Class<?> targetClass, final Class<?> rootClass, final int paramTypeNumber, Map<Integer, Type> childClassTypes) throws GenericsException {
    Type superclassType = klass.getGenericSuperclass();
    Map<TypeVariable<?>, Type> currentClassTypes = new HashMap<>();
    int z = 0;
    if (childClassTypes != null) {
        for (TypeVariable<?> variable : klass.getTypeParameters()) {
            currentClassTypes.put(variable, childClassTypes.get(z));
            z++;
        }
    }

    Map<Integer, Type> superClassesTypes = new HashMap<>();
    if (superclassType instanceof ParameterizedType) {
        int i = 0;
        for (final Type argType : ((ParameterizedType) superclassType).getActualTypeArguments()) {
            if (argType instanceof TypeVariable) {
                superClassesTypes.put(i, currentClassTypes.getOrDefault(argType, argType));
            } else {
                superClassesTypes.put(i, refineType(argType, currentClassTypes));
            }
            i++;
        }
    }

    if (klass != rootClass) {
        final Class<?> superClass = klass.getSuperclass();
        if (superClass == null)
            throw new GenericsException(String.format("Class [%s] not found on class parent hierarchy [%s]", rootClass, targetClass));
        return analyzeParameterizedTypes(superClass, targetClass, rootClass, paramTypeNumber, superClassesTypes);
    }
    return childClassTypes.get(paramTypeNumber);

}
</code>```

Example usage:

```<code>private class SomeClass<A, B, C, D, E, F> {}
private class SomeConfusingClass<A> extends SomeClass<List<Void>[], List<? extends A>[], List<? extends A[][][]>[][][], List<? extends String[]>[], Map<List<? extends A[]>, A[][]>[], A> {}
private class TestClass extends SomeConfusingClass<Void> {}

public static void main(String[] args) throws Exception {
    System.out.println(GenericsUtils.getParameterizedType(TestClass.class, SomeClass.class, 0));
    System.out.println(GenericsUtils.getParameterizedType(TestClass.class, SomeClass.class, 1));
    System.out.println(GenericsUtils.getParameterizedType(TestClass.class, SomeClass.class, 2));
    System.out.println(GenericsUtils.getParameterizedType(TestClass.class, SomeClass.class, 3));
    System.out.println(GenericsUtils.getParameterizedType(TestClass.class, SomeClass.class, 4));
    System.out.println(GenericsUtils.getParameterizedType(TestClass.class, SomeClass.class, 5));
}
</code>```

And results:

```<code>java.util.List<java.lang.Void>[]
java.util.List<? extends java.lang.Void>[]
java.util.List<? extends java.lang.Void[][][]>[][][]
java.util.List<? extends java.lang.String[]>[]
java.util.Map<java.util.List<? extends java.lang.Void[]>, java.lang.Void[][]>[]
class java.lang.Void
</code>```

Whole code with tests can be found here: https://gist.github.com/GotoFinal/33b9e282f270dbfe61907aa830c27587 or here: https://github.com/GotoFinal/generics-utils/tree/edge-cases-1

Based on OP original answer code, but with most of edge cases covered.

Body:
Suppose you have the following abstract java class:

public abstract class AbstractRequestHandler {
    I input;
    O output;
}

and the following child classes hierarchy:

public abstract class AbstractUserRequestHandler extends AbstractRequestHandler{...}
public abstract class AbstractUniversityRequestHandler extends AbstractUserRequestHandler{...}
public class StudentRequestHandler extends AbstractUniversityRequestHandler<Student>{...}
public class TeacherRequestHandler extends AbstractUniversityRequestHandler<Teacher>{...}

Suppose you need to use at a given point on the super class the generic type, for example in order to deserialize on the constructor the request json to the specific request object using gson library as follow:

public AbstractRequestHandler(final String inputJson) {
        input = new Gson().fromJson(inputJson,typeOfI);
}

You need the type of generic I within variable "typeOfI"

Is there a global solution that allows to get the generic type specified by a concrete child class that respects the following constraints?

The type is gotten at runtime regardless the child classes hierarchy ( that can be also more complex the one given as example on this question )

The developer just needs to define the generic extending the super class without manually specify the generic type somewhere on concrete child class ( for example on overrided method or constructor )

So that if you want to define a new concrete child that assign a new value to a generic you can just write the following concrete class for example:

public class StudentRequestHandler extends AbstractUniversityRequestHandler<Student>{

    public StudentRequestHandler(String inputJson) {
        super(inputJson);
    }

}

I found the following solutions but they don't respect both the asked solution constraints.

Solution that breaks constraint n°2

A solution could be to define an abstract method on the superclass as follow

protected abstract Type getRequestType();

and then implement it on every concrete child class that defines the generic:

public class StudentRequestHandler extends AbstractUniversityRequestHandler<Student>{

    public StudentRequestHandler(String inputJson) {
        super(inputJson);
    }

    @Override
    protected Type getRequestType() {
        return Student.class;
    }
}

Then the getRequestType() method can be used on constructor on the target superclass:

public AbstractRequestHandler(final String inputJson) {
        request = new Gson().fromJson(inputJson,getRequestType());
}

But even if it works regardless the child classes hierarchy ( respect constraint n°1 ) the developer should manually implement an abstract method on each concrete child class.

Solution that breaks constraint n°1

If the hierarchy is simple having only a direct child that extend from the target superclass, as for example:

public class TeacherRequestHandler extends AbstractRequestHandler<Teacher,String>{...}

a working solution has been proposed by @naikus ( https://stackoverflow.com/users/306602/naikus ) on the following stackoverflow thread:
Using a generic type of a subclass within it's abstract superclass?

However this doesn't work if the concrete class is not a direct child of the superclass that defines the generics ( as the one proposed as example on this question ).

Body:
Edit: after reading your answer and testing many other possible cases I decided to edit your code and re-write it to support all other possible edge cases to include tracking of generics nested deeply inside other generic types.

Sadly to support all cases we need a lot more code than you provided, generics are very tricky, like consider class like this:

private class SomeClass<A, B, C, D, E, F> {}

private class SomeConfusingClass<A> extends SomeClass<List<Void>[], List<? extends A>[], List<? extends A[][][]>[][][], List<? extends String[]>[], Map<List<? extends A[]>, A[][]>[], A> {}

private class TestClass extends SomeConfusingClass<Void> {}

To even start doing this we need to have own implementation of java generic types to later be able to construct types like List<String>[] as there is no way to create such type dynamically with raw java API.

This is pretty popular way of handling generic in libraries like that, you can see similar thing in jackson library and many more.

So we need implementation of GenericArrayType, ParameterizedType and WildcardType:

private static class ResolvedGenericArrayType implements GenericArrayType {
    private final Type genericComponentType;

    ResolvedGenericArrayType(Type genericComponentType) {
        this.genericComponentType = genericComponentType;
    }

    @Override
    public Type getGenericComponentType() {
        return genericComponentType;
    }

    public String toString() {
        return getGenericComponentType().toString() + "[]";
    }

    @Override
    public boolean equals(Object o) {
        if (o instanceof GenericArrayType) {
            GenericArrayType that = (GenericArrayType) o;
            return Objects.equals(genericComponentType, that.getGenericComponentType());
        } else
            return false;
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(genericComponentType);
    }
}

private static class ResolvedParameterizedType implements ParameterizedType {
    private final Type[] actualTypeArguments;
    private final Class<?> rawType;
    private final Type ownerType;

    private ResolvedParameterizedType(Type rawType, Type[] actualTypeArguments, Type ownerType) {
        this.actualTypeArguments = actualTypeArguments;
        this.rawType = (Class<?>) rawType;
        this.ownerType = (ownerType != null) ? ownerType : this.rawType.getDeclaringClass();
    }

    public Type[] getActualTypeArguments() {
        return actualTypeArguments.clone();
    }

    public Class<?> getRawType() {
        return rawType;
    }

    public Type getOwnerType() {
        return ownerType;
    }

    @Override
    public boolean equals(Object o) {
        if (!(o instanceof ParameterizedType)) {
            return false;
        }
        ParameterizedType that = (ParameterizedType) o;
        if (this == that)
            return true;
        Type thatOwner = that.getOwnerType();
        Type thatRawType = that.getRawType();
        return Objects.equals(ownerType, thatOwner) && Objects.equals(rawType, thatRawType) &&
                Arrays.equals(actualTypeArguments, that.getActualTypeArguments());
    }

    @Override
    public int hashCode() {
        return Arrays.hashCode(actualTypeArguments) ^
                Objects.hashCode(ownerType) ^
                Objects.hashCode(rawType);
    }

    public String toString() {
        StringBuilder sb = new StringBuilder();
        if (ownerType != null) {
            sb.append(ownerType.getTypeName());
            sb.append("$");
            if (ownerType instanceof ResolvedParameterizedType) {
                sb.append(rawType.getName().replace(((ResolvedParameterizedType) ownerType).rawType.getName() + "$", ""));
            } else
                sb.append(rawType.getSimpleName());
        } else
            sb.append(rawType.getName());
        if (actualTypeArguments != null) {
            StringJoiner sj = new StringJoiner(", ", "<", ">");
            sj.setEmptyValue("");
            for (Type t : actualTypeArguments) {
                sj.add(t.getTypeName());
            }
            sb.append(sj.toString());
        }
        return sb.toString();
    }
}

private static class ResolvedWildcardType implements WildcardType {
    private final Type[] upperBounds;
    private final Type[] lowerBounds;

    public ResolvedWildcardType(Type[] upperBounds, Type[] lowerBounds) {
        this.upperBounds = upperBounds;
        this.lowerBounds = lowerBounds;
    }

    public Type[] getUpperBounds() {
        return upperBounds.clone();
    }

    public Type[] getLowerBounds() {
        return lowerBounds.clone();
    }

    public String toString() {
        Type[] lowerBounds = getLowerBounds();
        Type[] bounds = lowerBounds;
        StringBuilder sb = new StringBuilder();
        if (lowerBounds.length > 0)
            sb.append("? super ");
        else {
            Type[] upperBounds = getUpperBounds();
            if (upperBounds.length > 0 && !upperBounds[0].equals(Object.class)) {
                bounds = upperBounds;
                sb.append("? extends ");
            } else
                return "?";
        }
        StringJoiner sj = new StringJoiner(" & ");
        for (Type bound : bounds) {
            sj.add(bound.getTypeName());
        }
        sb.append(sj.toString());
        return sb.toString();
    }

    @Override
    public boolean equals(Object o) {
        if (o instanceof WildcardType) {
            WildcardType that = (WildcardType) o;
            return Arrays.equals(this.getLowerBounds(), that.getLowerBounds()) && Arrays.equals(this.getUpperBounds(), that.getUpperBounds());
        } else
            return false;
    }

    @Override
    public int hashCode() {
        Type[] lowerBounds = getLowerBounds();
        Type[] upperBounds = getUpperBounds();
        return Arrays.hashCode(lowerBounds) ^ Arrays.hashCode(upperBounds);
    }
}

You can basically copy them from JDK and just do some cleanup.

Next utility we need is a function to validate at the end if we did everything right, like we don't want to return Map<List<? extends X>[]> where X is still not resolved TypeVariable:

private static boolean isDefined(Type type) {
    if (type instanceof Class) {
        return true;
    }
    if (type instanceof GenericArrayType) {
        return isDefined(((GenericArrayType) type).getGenericComponentType());
    }
    if (type instanceof WildcardType) {
        for (Type lowerBound : ((WildcardType) type).getLowerBounds()) {
            if (!isDefined(lowerBound)) {
                return false;
            }
        }
        for (Type upperBound : ((WildcardType) type).getUpperBounds()) {
            if (!isDefined(upperBound)) {
                return false;
            }
        }
        return true;
    }
    if (!(type instanceof ParameterizedType)) {
        return false;
    }
    for (Type typeArgument : ((ParameterizedType) type).getActualTypeArguments()) {
        if (!isDefined(typeArgument)) {
            return false;
        }
    }
    return true;
}

Simple recursive function will do this for us. We just check for every possible generic type and check if every member of it is also defined, and unless we will find some hidden TypeVariable we are fine.

Main function can stay the same as in your code, we only will edit that one check at the end to use our new function:

public static Type getParameterizedType(Class<?> klass, Class<?> rootClass, int paramTypeNumber) throws GenericsException {

    int targetClassParametersNumber = rootClass.getTypeParameters().length;
    if (targetClassParametersNumber == 0) {
        throw new GenericsException(String.format("Target class [%s] has no parameters type", rootClass.getName()));
    } else if (targetClassParametersNumber - 1 < paramTypeNumber)
        throw new GenericsException(String.format("Target class [%s] has parameters type which index start from [0] to [%s]. You requested instead parameter with index [%s]", rootClass, paramTypeNumber - 1, targetClassParametersNumber));

    Type type = analyzeParameterizedTypes(klass, klass, rootClass, paramTypeNumber, null);
    if (!isDefined(type))
        throw new GenericsException(String.format("Parameter [%s] with index [%d] defined on class [%s] has not been valued yet on child class [%s]", type, paramTypeNumber, rootClass.getName(), klass.getName()));
    return type;
}

Now lets work on our main

public static Type analyzeParameterizedTypes(final Class<?> klass, final Class<?> targetClass, final Class<?> rootClass, final int paramTypeNumber, Map<Integer, Type> childClassTypes) throws GenericsException {

function, the begging stays the same, we collect all TypeVariable to simple map, keeping already collected information from previous loop on previous class.

    Type superclassType = klass.getGenericSuperclass();
    Map<TypeVariable<?>, Type> currentClassTypes = new HashMap<>();
    int z = 0;
    if (childClassTypes != null) {
        for (TypeVariable<?> variable : klass.getTypeParameters()) {
            currentClassTypes.put(variable, childClassTypes.get(z));
            z++;
        }
    }

Then we have our loop collecting and refining our type arguments:

    Map<Integer, Type> superClassesTypes = new HashMap<>();
    if (superclassType instanceof ParameterizedType) {
        int i = 0;
        for (final Type argType : ((ParameterizedType) superclassType).getActualTypeArguments()) {
            if (argType instanceof TypeVariable) {
                superClassesTypes.put(i, currentClassTypes.containsKey(argType) ? currentClassTypes.get(argType) : argType);
            } else {
                superClassesTypes.put(i, refineType(klass, argType, currentClassTypesByName));
            }
            i++;
        }
    }

There 2 paths for each type argument, if its TypeVariable we just keep tracking it, and if its anything else we try to "refine" it from any possible references to TypeVariable. This is the most complicated process of this code, and this is why we needed all these classes above.

We start from this simple recursive dispatch method that handles all possible types:

private static Type refineType(Type type, Map<TypeVariable<?>, Type> typeVariablesMap) throws GenericsException {
    if (type instanceof Class) {
        return type;
    }
    if (type instanceof GenericArrayType) {
        return refineArrayType((GenericArrayType) type, typeVariablesMap);
    }
    if (type instanceof ParameterizedType) {
        return refineParameterizedType((ParameterizedType) type, typeVariablesMap);
    }
    if (type instanceof WildcardType) {
        return refineWildcardType((WildcardType) type, typeVariablesMap);
    }
    if (type instanceof TypeVariable) {
        return typeVariablesMap.get(type);
    }
    throw new GenericsException("Unsolvable generic type: " + type);
}

And small utility method to run it on array of types:

private static Type[] refineTypes(Type[] types, Map<TypeVariable<?>, Type> typeVariablesMap) throws GenericsException {
    Type[] refinedTypes = new Type[types.length];
    for (int i = 0; i < types.length; i++) {
        refinedTypes[i] = refineType(types[i], typeVariablesMap);
    }
    return refinedTypes;
}

Each type goes to own function, or if its TypeVariable we just fetch resolved one from map. Note that this can return null, and I did not handle it here. This could be improved later. For classes we don't need to do anything so we can just return class itself.

For GenericArrayType we need to first find out how many dimension such array might have (this could be handled by recursion in our refine method too, but then its a bit harder to debug in my opinion):

private static int getArrayDimensions(GenericArrayType genericArrayType) {
    int levels = 1;
    GenericArrayType currentArrayLevel = genericArrayType;
    while (currentArrayLevel.getGenericComponentType() instanceof GenericArrayType) {
        currentArrayLevel = (GenericArrayType) currentArrayLevel.getGenericComponentType();
        levels += 1;
    }
    return levels;
}

Then we want to extract that nested component type of array, so for List<A>[][][] we want just List<A>:

private static Type getArrayNestedComponentType(GenericArrayType genericArrayType) {
    GenericArrayType currentArrayLevel = genericArrayType;
    while (currentArrayLevel.getGenericComponentType() instanceof GenericArrayType) {
        currentArrayLevel = (GenericArrayType) currentArrayLevel.getGenericComponentType();
    }
    return currentArrayLevel.getGenericComponentType();
}

And then we need to refine this type, so our List<A> will change to eg List<String>:

    Type arrayComponentType = refineType(getArrayNestedComponentType(genericArrayType), typeVariablesMap);

And rebuild our generic structure using refined type, so our created List<String> will change back to List<String>[][][]:

private static Type buildArrayType(Type componentType, int levels) throws GenericsException {
    if (componentType instanceof Class) {
        return Array.newInstance(((Class<?>) componentType), new int[levels]).getClass();
    } else if (componentType instanceof ParameterizedType) {
        GenericArrayType genericArrayType = new ResolvedGenericArrayType(componentType);
        for (int i = 1; i < levels; i++) {
            genericArrayType = new ResolvedGenericArrayType(genericArrayType);
        }
        return genericArrayType;
    } else {
        throw new GenericsException("Array can't be of generic type");
    }
}

And whole function looks like this:

private static Type refineArrayType( GenericArrayType genericArrayType, Map<TypeVariable<?>, Type> typeVariablesMap) throws GenericsException {
    int levels = getArrayDimensions(genericArrayType);
    Type arrayComponentType = refineType(getArrayNestedComponentType(genericArrayType), typeVariablesMap);
    return buildArrayType(arrayComponentType, levels);
}

For ParameterizedType its much simpler, we just refine type arguments, and create new ParameterizedType instance with these refined arguments:

private static Type refineParameterizedType(ParameterizedType parameterizedType, Map<TypeVariable<?>, Type> typeVariablesMap) throws GenericsException {
    Type[] refinedTypeArguments = refineTypes(parameterizedType.getActualTypeArguments(), typeVariablesMap);
    return new ResolvedParameterizedType(parameterizedType.getRawType(), refinedTypeArguments, parameterizedType.getOwnerType());
}

Same for WildcardType:

private static Type refineWildcardType(WildcardType wildcardType, Map<TypeVariable<?>, Type> typeVariablesMap) throws GenericsException {
    Type[] refinedUpperBounds = refineTypes(wildcardType.getUpperBounds(), typeVariablesMap);
    Type[] refinedLowerBounds = refineTypes(wildcardType.getLowerBounds(), typeVariablesMap);
    return new ResolvedWildcardType(refinedUpperBounds, refinedLowerBounds);
}

And this leaves us with whole analyze function looking like this:

public static Type analyzeParameterizedTypes(final Class<?> klass, final Class<?> targetClass, final Class<?> rootClass, final int paramTypeNumber, Map<Integer, Type> childClassTypes) throws GenericsException {
    Type superclassType = klass.getGenericSuperclass();
    Map<TypeVariable<?>, Type> currentClassTypes = new HashMap<>();
    int z = 0;
    if (childClassTypes != null) {
        for (TypeVariable<?> variable : klass.getTypeParameters()) {
            currentClassTypes.put(variable, childClassTypes.get(z));
            z++;
        }
    }

    Map<Integer, Type> superClassesTypes = new HashMap<>();
    if (superclassType instanceof ParameterizedType) {
        int i = 0;
        for (final Type argType : ((ParameterizedType) superclassType).getActualTypeArguments()) {
            if (argType instanceof TypeVariable) {
                superClassesTypes.put(i, currentClassTypes.getOrDefault(argType, argType));
            } else {
                superClassesTypes.put(i, refineType(argType, currentClassTypes));
            }
            i++;
        }
    }

    if (klass != rootClass) {
        final Class<?> superClass = klass.getSuperclass();
        if (superClass == null)
            throw new GenericsException(String.format("Class [%s] not found on class parent hierarchy [%s]", rootClass, targetClass));
        return analyzeParameterizedTypes(superClass, targetClass, rootClass, paramTypeNumber, superClassesTypes);
    }
    return childClassTypes.get(paramTypeNumber);

}

Example usage:

private class SomeClass<A, B, C, D, E, F> {}
private class SomeConfusingClass<A> extends SomeClass<List<Void>[], List<? extends A>[], List<? extends A[][][]>[][][], List<? extends String[]>[], Map<List<? extends A[]>, A[][]>[], A> {}
private class TestClass extends SomeConfusingClass<Void> {}

public static void main(String[] args) throws Exception {
    System.out.println(GenericsUtils.getParameterizedType(TestClass.class, SomeClass.class, 0));
    System.out.println(GenericsUtils.getParameterizedType(TestClass.class, SomeClass.class, 1));
    System.out.println(GenericsUtils.getParameterizedType(TestClass.class, SomeClass.class, 2));
    System.out.println(GenericsUtils.getParameterizedType(TestClass.class, SomeClass.class, 3));
    System.out.println(GenericsUtils.getParameterizedType(TestClass.class, SomeClass.class, 4));
    System.out.println(GenericsUtils.getParameterizedType(TestClass.class, SomeClass.class, 5));
}

And results:

java.util.List<java.lang.Void>[]
java.util.List<? extends java.lang.Void>[]
java.util.List<? extends java.lang.Void[][][]>[][][]
java.util.List<? extends java.lang.String[]>[]
java.util.Map<java.util.List<? extends java.lang.Void[]>, java.lang.Void[][]>[]
class java.lang.Void

Whole code with tests can be found here: https://gist.github.com/GotoFinal/33b9e282f270dbfe61907aa830c27587 or here: https://github.com/GotoFinal/generics-utils/tree/edge-cases-1

Based on OP original answer code, but with most of edge cases covered.


来源: stackexchange

问:
Reactive form select tag validation
I am working on reactive form validation on select tag validation and its validation is not working. This is a basic reactive form validation and I have done validation of other fields, they are working, but the one validation on select tag (State input field) is not working.

html file

```<code><div class="container">
  <form [formGroup]="info" (ngSubmit)="onSubmit">
    <h1>Info</h1>
    <div>
      <label>First Name</label>
      <input
        type="text"
        formControlName="firstName"
        class="form-control"
        [ngClass]="{ 'is-invalid': f.firstName.touched && f.firstName.errors }"
      />
      <div
        *ngIf="f.firstName.touched && f.firstName.errors"
        class="alert alert-danger"
      >
        <div *ngIf="f.firstName.errors.required">First Name is required</div>
        <div *ngIf="f.firstName.errors.minlength">Minimum 3 characters</div>
        <div *ngIf="f.firstName.errors.maxlength">Maximum 10 characters</div>
        <div *ngIf="f.firstName.errors.pattern">Only alphabets</div>
      </div>
    </div>

    <div>
      <label>Last Name</label>
      <input
        type="text"
        formControlName="lastName"
        class="form-control"
        [ngClass]="{'is-invalid':f.lastName.touched && f.lastName.errors}"
      />
      <div *ngIf="f.lastName.touched && f.lastName.errors">
        <div *ngIf="f.lastName.errors.required">Last name required</div>
        <div *ngIf="f.lastName.errors.minlength">Minimum 3 characters</div>
        <div *ngIf="f.lastName.errors.maxlength">Minimum 10 characters</div>
      </div>
    </div>

    <div>
      <label for="">Gender</label>

      <input
        type="radio"
        formControlName="gender"
        class="form-control"
        value="male"
      /><span>male</span>
      <input
        type="radio"
        formControlName="gender"
        class="form-control"
        value="female"
      /><span>female</span>
      <input
        type="radio"
        formControlName="gender"
        class="form-control"
        value="other"
      /><span>other</span>

      <div>
        <div *ngIf="f.gender.touched && f.gender.errors">
          <div>Gender required</div>
        </div>
      </div>
    </div>

    <div>
      <label for="state">State</label>
      <select id="state" formControlName="state" class="form-control"
      [ngClass]="{'is-invalid':f.state.touched && f.state.errors}">
        <option value=""></option>
        <option value="Delhi">Delhi</option>
        <option value="UP">UP</option>
        <option value="Karnataka">Karnataka</option>
        <option value="Bihar">Bihar</option>
        <div>
        <div *ngIf="f.state.errors.touched && f.state.errors">
          <div *ngIf="f.state.errors.required">state required</div>

        </div></div>
      </select>
    </div>

    <div>
      <label for="qualification">qualification</label>
      <input
        type="checkbox"
        formControlName="qualification"
        class="form-control"
        value="Graduate"
      /><span>Graduate</span>
      <input
        type="checkbox"
        formControlName="qualification"
        class="form-control"
        value="Post Graduate"
      /><label>Post Graduate</label>

      <div>
        <div *ngIf="f.qualification.touched && f.qualification.errors">
          <div>qualification required</div>
        </div>
      </div>
    </div>
    <div>
      <button type="submit" (click)="onSubmit" [disabled]="info.invalid">
        submit
      </button>
    </div>
  </form>
</div>
</code>```

ts file

```<code>import { Component,OnInit } from "@angular/core";
import { FormGroup,FormBuilder, Validators } from "@angular/forms";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit{
  title = "CodeSandbox";
  info: FormGroup;
  submitted:boolean;
  regex:any="^[A-Za-z]*";

  constructor(private fb:FormBuilder){

  }
  ngOnInit(){
    this.valueInfo();
  }
  valueInfo(){
    this.info=this.fb.group({
      firstName:['',[Validators.required,
        Validators.minLength(3),
        Validators.maxLength(10),
        Validators.pattern(this.regex)]],
      lastName:['',[Validators.required,
        Validators.minLength(3),
        Validators.maxLength(10),
        Validators.pattern(this.regex)]],
      gender:['',Validators.required],
      state:['',Validators.required],
      qualification:['',Validators.required]
})
  }
  get f(){
    return this.info.controls;
  }
}
</code>```

答:
You have used  f.state.errors.touched it must be just f.state.touched

```<code>  <div *ngIf="f.state.touched && f.state.errors">
              <div *ngIf="f.state.errors.required">state required</div>

            </div></div>
</code>```

Edit:

I also noticed that you have put the div which is meant to be outside the select HTMLelement show the error message inside the Select Tag, as shown below.

```<code>  <div>
      <label for="state">State</label>
      <select id="state" formControlName="state" class="form-control"
      [ngClass]="{'is-invalid':f.state.touched && f.state.errors}">
         <option value=""></option>
        <option value="Delhi">Delhi</option>
        <option value="UP">UP</option>
        <option value="Karnataka">Karnataka</option>
        <option value="Bihar">Bihar</option>

      </select>
         <div>
        <div *ngIf="f.state.touched && f.state.errors">
          <div *ngIf="f.state.errors.required">state required</div>

        </div></div>
    </div>
</code>```

I have created a stackblitz.com with the all the change.

ContentLicense: CC BY-SA 4.0

Title: Reactive form select tag validation

Body:
I am working on reactive form validation on select tag validation and its validation is not working. This is a basic reactive form validation and I have done validation of other fields, they are working, but the one validation on select tag (State input field) is not working.

html file

  <form [formGroup]="info" (ngSubmit)="onSubmit">

Info

      First Name
      <input
        type="text"
        formControlName="firstName"
        class="form-control"
        [ngClass]="{ 'is-invalid': f.firstName.touched && f.firstName.errors }"
      />

First Name is required

Minimum 3 characters

Maximum 10 characters

Only alphabets

      Last Name
      <input
        type="text"
        formControlName="lastName"
        class="form-control"
        [ngClass]="{'is-invalid':f.lastName.touched && f.lastName.errors}"
      />

Last name required

Minimum 3 characters

Minimum 10 characters

      Gender

      <input
        type="radio"
        formControlName="gender"
        class="form-control"
        value="male"
      />male
      <input
        type="radio"
        formControlName="gender"
        class="form-control"
        value="female"
      />female
      <input
        type="radio"
        formControlName="gender"
        class="form-control"
        value="other"
      />other

Gender required

      State
      <select id="state" formControlName="state" class="form-control"
      [ngClass]="{'is-invalid':f.state.touched && f.state.errors}">
        <option value=""></option>
        <option value="Delhi">Delhi</option>
        <option value="UP">UP</option>
        <option value="Karnataka">Karnataka</option>
        <option value="Bihar">Bihar</option>

state required

      </select>

      qualification
      <input
        type="checkbox"
        formControlName="qualification"
        class="form-control"
        value="Graduate"
      />Graduate
      <input
        type="checkbox"
        formControlName="qualification"
        class="form-control"
        value="Post Graduate"
      />Post Graduate

qualification required

      <button type="submit" (click)="onSubmit" [disabled]="info.invalid">
        submit
      </button>

  </form>

ts file

import { Component,OnInit } from "@angular/core";
import { FormGroup,FormBuilder, Validators } from "@angular/forms";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit{
  title = "CodeSandbox";
  info: FormGroup;
  submitted:boolean;
  regex:any="^[A-Za-z]*";

  constructor(private fb:FormBuilder){

  }
  ngOnInit(){
    this.valueInfo();
  }
  valueInfo(){
    this.info=this.fb.group({
      firstName:['',[Validators.required,
        Validators.minLength(3),
        Validators.maxLength(10),
        Validators.pattern(this.regex)]],
      lastName:['',[Validators.required,
        Validators.minLength(3),
        Validators.maxLength(10),
        Validators.pattern(this.regex)]],
      gender:['',Validators.required],
      state:['',Validators.required],
      qualification:['',Validators.required]
})
  }
  get f(){
    return this.info.controls;
  }
}

Body:
You have used  f.state.errors.touched it must be just f.state.touched

  <div *ngIf="f.state.touched && f.state.errors">
              <div *ngIf="f.state.errors.required">state required</div>

            </div></div>

Edit:

I also noticed that you have put the div which is meant to be outside the select HTMLelement show the error message inside the Select Tag, as shown below.

  <div>
      <label for="state">State</label>
      <select id="state" formControlName="state" class="form-control"
      [ngClass]="{'is-invalid':f.state.touched && f.state.errors}">
         <option value=""></option>
        <option value="Delhi">Delhi</option>
        <option value="UP">UP</option>
        <option value="Karnataka">Karnataka</option>
        <option value="Bihar">Bihar</option>

      </select>
         <div>
        <div *ngIf="f.state.touched && f.state.errors">
          <div *ngIf="f.state.errors.required">state required</div>

        </div></div>
    </div>

I have created a stackblitz.com with the all the change.


问:
replace all odd values in vector with coresponing value from new vector
Given following vectors:

```<code>std::vector<int> foo{1,2,3,4,5,6,7};
std::vector<int> bar{10,20,30,40,50,60,70};
</code>```

In the end I want foo to contain values { 10, 2, 30, 4, 50, 6, 70 } meaning replacing all odd values.

I've tried the algorithm std::replace_if, but how to access the bars corresponding value?

```<code>// replace_copy_if example
#include <iostream>     // std::cout
#include <algorithm>    // std::replace_copy_if
#include <vector>       // std::vector

bool IsOdd (int i) { return ((i%2)==1); }

int main () {
  std::vector<int> foo{1,2,3,4,5,6,7};
  std::vector<int> bar{10,20,30,40,50,60,70};

  std::replace_if (foo.begin(), foo.end(), IsOdd, 0);

  std::cout << "foo contains:";
  for (auto i: foo){ std::cout << ' ' << i; }
  std::cout << '\n';

  return 0;
}

// output         : foo contains: 0 2 0 4 0 6 0
// desired output : foo contains: 10 2 30 4 50 6 70
</code>```

答:
```<code>// replace_copy_if example
#include <iostream>     // std::cout
#include <vector>       // std::vector

int main () {
  std::vector<int> foo{1,2,3,4,5,6,7};
  std::vector<int> bar{10,20,30,40,50,60,70};

  for (size_t i = 0; i < bar.size(); i++)
  {
     if (foo[i]%2==1) foo[i]=bar[i];
  }

  std::cout << "bar contains:";
  for (auto i: foo){ std::cout << ' ' << i; }
  std::cout << '\n';

  return 0;
}
</code>```

Body:
Given following vectors:

std::vector<int> foo{1,2,3,4,5,6,7};
std::vector<int> bar{10,20,30,40,50,60,70};

In the end I want foo to contain values { 10, 2, 30, 4, 50, 6, 70 } meaning replacing all odd values.

I've tried the algorithm std::replace_if, but how to access the bars corresponding value?

// replace_copy_if example
#include <iostream>     // std::cout
#include <algorithm>    // std::replace_copy_if
#include <vector>       // std::vector

bool IsOdd (int i) { return ((i%2)==1); }

int main () {
  std::vector<int> foo{1,2,3,4,5,6,7};
  std::vector<int> bar{10,20,30,40,50,60,70};

  std::replace_if (foo.begin(), foo.end(), IsOdd, 0);

  std::cout << "foo contains:";
  for (auto i: foo){ std::cout << ' ' << i; }
  std::cout << '\n';

  return 0;
}

// output         : foo contains: 0 2 0 4 0 6 0
// desired output : foo contains: 10 2 30 4 50 6 70


问:
React hooks - Remove multi object from array and update state
How to delete multiple objects of array  and update the state?
I have selected multiple items from checkbox
This is the selected item [5, 4, 3]
I want to remove all items in array based on id and update the state
This is my code

```<code> const [products, setProducts] = useState();

 const DeleteProducts = () => {
  const selectedItems = [5, 4, 3];

    selectedItems.forEach(function(p) {
      setProducts(products.filter(prd => prd.id !== p));
    });
}
</code>```

Its removing only one item at time, but I selected 3 items. How to show remaining items except 3 selected items in products state?
Thanks

答:
You can simplify it to a single filter function:</p>

```<code>const DeleteProducts = () => {
  setProducts(prevProducts => {
    return prevProducts.filter(p => ! p.selected);
  });
}
</code>```

Body:
How to delete multiple objects of array  and update the state?
I have selected multiple items from checkbox
This is the selected item [5, 4, 3]
I want to remove all items in array based on id and update the state
This is my code

 const [products, setProducts] = useState();

 const DeleteProducts = () => {
  const selectedItems = [5, 4, 3];

    selectedItems.forEach(function(p) {
      setProducts(products.filter(prd => prd.id !== p));
    });
}

Its removing only one item at time, but I selected 3 items. How to show remaining items except 3 selected items in products state?
Thanks

Body:
You can simplify it to a single filter function:

const DeleteProducts = () => {
  setProducts(prevProducts => {
    return prevProducts.filter(p => ! p.selected);
  });
}


问:
How to find the condition of SQL WHERE clause pragmatically
I have created an API Gateway that will accept an SQL statement, run the statement against the database and return its result as a response. For every SQL statement, I receive as input I have to append a WHERE condition in the SQL. For example:-

Input SQL-  SELECT * FROM contacts WHERE last_name = 'Johnson';

Append Condition- country = 'India'

New SQL-  SELECT * FROM contacts WHERE last_name = 'Johnson' AND (country = 'India');

For the above SQL, it was easy to find the WHERE keyword and its condition as it was at the end. But for some SQL we can have OFFSET, HAVING, ORDER BY, GROUP BY, FETCH NEXT and many more after the WHERE. So, cannot find a robust way to find out the WHERE condition and append to it.

Possible usage of WHERE is as below-

```<code>SELECT *                          // Condition With Spaces
FROM contacts
WHERE last_name = 'Johnson';

SELECT *                          // Condition Without Spaces
FROM contacts
WHERE last_name='Johnson';

SELECT *                          // Multiple Conditions
FROM suppliers
WHERE ((state = 'Florida' AND supplier_name = 'IBM')
OR (supplier_id > 5000)) AND

SELECT email FROM emailTable       // WHERE With OFFSET
WHERE user_id=3
ORDER BY Id
OFFSET 10 ROWS
FETCH NEXT 10 ROWS ONLY;

SELECT column_name(s)            // WHERE With GROUP BY, HAVING, ORDER BY
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);
</code>```

One approach would be to list down all the keywords that come after WHERE to find its condition. But I want to check if there is any better approach for this. Any suggestions or documents will be appreciated.

答:
Use subqueries:

```<code>select q.*
from (<query>) q  -- insert query here
<where>           -- insert other code here
</code>```

So, this query becomes:

```<code>SELECT q.*
FROM (SELECT *
      FROM contacts
     ) q
WHERE last_name = 'Johnson';
</code>```

If you find that you also need to append an ORDER BY/OFFSET, I would recommend passing that in as a separate argument -- as you do with the WHERE.

Body:
I have created an API Gateway that will accept an SQL statement, run the statement against the database and return its result as a response. For every SQL statement, I receive as input I have to append a WHERE condition in the SQL. For example:-

Input SQL-  SELECT * FROM contacts WHERE last_name = 'Johnson';

Append Condition- country = 'India'

New SQL-  SELECT * FROM contacts WHERE last_name = 'Johnson' AND (country = 'India');

For the above SQL, it was easy to find the WHERE keyword and its condition as it was at the end. But for some SQL we can have OFFSET, HAVING, ORDER BY, GROUP BY, FETCH NEXT and many more after the WHERE. So, cannot find a robust way to find out the WHERE condition and append to it.

Possible usage of WHERE is as below-

SELECT *                          // Condition With Spaces
FROM contacts
WHERE last_name = 'Johnson';

SELECT *                          // Condition Without Spaces
FROM contacts
WHERE last_name='Johnson';

SELECT *                          // Multiple Conditions
FROM suppliers
WHERE ((state = 'Florida' AND supplier_name = 'IBM')
OR (supplier_id > 5000)) AND

SELECT email FROM emailTable       // WHERE With OFFSET
WHERE user_id=3
ORDER BY Id
OFFSET 10 ROWS
FETCH NEXT 10 ROWS ONLY;

SELECT column_name(s)            // WHERE With GROUP BY, HAVING, ORDER BY
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);

One approach would be to list down all the keywords that come after WHERE to find its condition. But I want to check if there is any better approach for this. Any suggestions or documents will be appreciated.

Body:
Use subqueries:

select q.*
from (<query>) q  -- insert query here
<where>           -- insert other code here

So, this query becomes:

SELECT q.*
FROM (SELECT *
      FROM contacts
     ) q
WHERE last_name = 'Johnson';

If you find that you also need to append an ORDER BY/OFFSET, I would recommend passing that in as a separate argument -- as you do with the WHERE.


问:
django bulk user import user django-import-export
i want use import export to bulk user import in django

i get a file include list of users then create users according to file rows

i try implement before_import like this

```<code>from import_export import resources
class UserResource(resources.ModelResource):
    def before_import(self,dataset, dry_run, **kwargs):
        #dataset is  tablib.Dataset()
        for i in dataset:
            i[1]=make_password(i[1])
        return super(UserResource, self).before_import(dataset, dry_run, **kwargs)
</code>```

but it return tuple' object does not support item assignment

答:
I hope you are trying to hash your password before importing.
it helps you:</p>

```<code>    from import_export import resources, fields
    from import_export.admin import ImportExportModelAdmin
    from django.contrib.auth.hashers import make_password

    class UserResource(resources.ModelResource):

       groups = fields.Field(
           column_name='group_name',
           attribute='groups',
           widget=ManyToManyWidget(Group, ',','name')
       )
       def before_import_row(self,row, **kwargs):
           value = row['password']
           row['password'] = make_password(value)
       class Meta:
           model = User
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i want use import export to bulk user import in django

i get a file include list of users then create users according to file rows

i try implement before_import like this

from import_export import resources
class UserResource(resources.ModelResource):
    def before_import(self,dataset, dry_run, **kwargs):
        #dataset is  tablib.Dataset()
        for i in dataset:
            i[1]=make_password(i[1])
        return super(UserResource, self).before_import(dataset, dry_run, **kwargs)

but it return tuple' object does not support item assignment

Body:
I hope you are trying to hash your password before importing.
it helps you:

    from import_export import resources, fields
    from import_export.admin import ImportExportModelAdmin
    from django.contrib.auth.hashers import make_password

    class UserResource(resources.ModelResource):

       groups = fields.Field(
           column_name='group_name',
           attribute='groups',
           widget=ManyToManyWidget(Group, ',','name')
       )
       def before_import_row(self,row, **kwargs):
           value = row['password']
           row['password'] = make_password(value)
       class Meta:
           model = User


问:
Xodus producing a huge file when passing from key-value (Environment) to relational (Entity)
I originally created a key-value database with Xodus Entity that created a small, 2GB database:

```<code>public static void main(String[] args) throws Exception{

        if (args.length != 2){
            throw new Exception("Argument missing. Current number of arguments: " + args.length);
        }

        long offset = Long.parseLong(args[0]);
        long chunksize = Long.parseLong(args[1]);

        Path pathBabelNet = Paths.get("/mypath/BabelNet-API-3.7/config");
        BabelNetLexicalizationDataSource dataSource = new BabelNetLexicalizationDataSource(pathBabelNet);
        Map<String, List<String>> data = new HashMap<String, List<String>>();
        data = dataSource.getDataChunk(offset, chunksize);

        jetbrains.exodus.env.Environment env = Environments.newInstance(".myAppData");
        final Transaction txn = env.beginTransaction();
        Store store = env.openStore("xodus-lexicalizations", StoreConfig.WITHOUT_DUPLICATES, txn);

        for (Map.Entry<String, List<String>> entry : data.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue().get(0);

            store.put(txn, StringBinding.stringToEntry(key), StringBinding.stringToEntry(value));
        }

        txn.commit();
        env.close();

    }
</code>```

I used a batch script to do this in chunks:

```<code>#!/bin/bash

START_TIME=$SECONDS

chunksize=50000

for ((offset=0; offset<165622128;))
do
    echo $offset;
    java -Xmx10g -jar /path/to/jar.jar $offset $chunksize
    offset=$((offset+(chunksize*12)))
done

ELAPSED_TIME=$(($SECONDS - $START_TIME))

echo $ELAPSED_TIME;
</code>```

Now I changed it so it is relational:

```<code>public static void main(String[] args) throws Exception{

        if (args.length != 2){
            throw new Exception("Argument missing. Current number of arguments: " + args.length);
        }

        long offset = Long.parseLong(args[0]);
        long chunksize = Long.parseLong(args[1]);

        Path pathBabelNet = Paths.get("/mypath/BabelNet-API-3.7/config");
        BabelNetLexicalizationDataSource dataSource = new BabelNetLexicalizationDataSource(pathBabelNet);
        Map<String, List<String>> data = new HashMap<String, List<String>>();
        data = dataSource.getDataChunk(offset, chunksize);

        PersistentEntityStore store = PersistentEntityStores.newInstance("lexicalizations-test");
        final StoreTransaction txn = store.beginTransaction();

        Entity synsetID;
        Entity lexicalization;
        String id;

        for (Map.Entry<String, List<String>> entry : data.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue().get(0);

            synsetID = txn.newEntity("SynsetID");
            synsetID.setProperty("synsetID", key);

            lexicalization = txn.newEntity("Lexicalization");
            lexicalization.setProperty("lexicalization", value);

            lexicalization.addLink("synsetID", synsetID);
            synsetID.addLink("lexicalization", lexicalization);

            txn.flush();
        }

        txn.commit();
    }
</code>```

And this created a file over 17GB and it only stopped because I ran out of memory. I understand that it will be larger because it has to store the links, among other things, but ten times bigger? What am I doing wrong?

答: For some reason removing the txn.flush() fixes everything. Now it's just 5.5GB.

Body:
I originally created a key-value database with Xodus Entity that created a small, 2GB database:

public static void main(String[] args) throws Exception{

        if (args.length != 2){
            throw new Exception("Argument missing. Current number of arguments: " + args.length);
        }

        long offset = Long.parseLong(args[0]);
        long chunksize = Long.parseLong(args[1]);

        Path pathBabelNet = Paths.get("/mypath/BabelNet-API-3.7/config");
        BabelNetLexicalizationDataSource dataSource = new BabelNetLexicalizationDataSource(pathBabelNet);
        Map<String, List<String>> data = new HashMap<String, List<String>>();
        data = dataSource.getDataChunk(offset, chunksize);

        jetbrains.exodus.env.Environment env = Environments.newInstance(".myAppData");
        final Transaction txn = env.beginTransaction();
        Store store = env.openStore("xodus-lexicalizations", StoreConfig.WITHOUT_DUPLICATES, txn);

        for (Map.Entry<String, List<String>> entry : data.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue().get(0);

            store.put(txn, StringBinding.stringToEntry(key), StringBinding.stringToEntry(value));
        }

        txn.commit();
        env.close();

    }

I used a batch script to do this in chunks:

#!/bin/bash

START_TIME=$SECONDS

chunksize=50000

for ((offset=0; offset<165622128;))
do
    echo $offset;
    java -Xmx10g -jar /path/to/jar.jar $offset $chunksize
    offset=$((offset+(chunksize*12)))
done

ELAPSED_TIME=$(($SECONDS - $START_TIME))

echo $ELAPSED_TIME;

Now I changed it so it is relational:

public static void main(String[] args) throws Exception{

        if (args.length != 2){
            throw new Exception("Argument missing. Current number of arguments: " + args.length);
        }

        long offset = Long.parseLong(args[0]);
        long chunksize = Long.parseLong(args[1]);

        Path pathBabelNet = Paths.get("/mypath/BabelNet-API-3.7/config");
        BabelNetLexicalizationDataSource dataSource = new BabelNetLexicalizationDataSource(pathBabelNet);
        Map<String, List<String>> data = new HashMap<String, List<String>>();
        data = dataSource.getDataChunk(offset, chunksize);

        PersistentEntityStore store = PersistentEntityStores.newInstance("lexicalizations-test");
        final StoreTransaction txn = store.beginTransaction();

        Entity synsetID;
        Entity lexicalization;
        String id;

        for (Map.Entry<String, List<String>> entry : data.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue().get(0);

            synsetID = txn.newEntity("SynsetID");
            synsetID.setProperty("synsetID", key);

            lexicalization = txn.newEntity("Lexicalization");
            lexicalization.setProperty("lexicalization", value);

            lexicalization.addLink("synsetID", synsetID);
            synsetID.addLink("lexicalization", lexicalization);

            txn.flush();
        }

        txn.commit();
    }

And this created a file over 17GB and it only stopped because I ran out of memory. I understand that it will be larger because it has to store the links, among other things, but ten times bigger? What am I doing wrong?


问:
Delete all indices in elasticsearch
does anyone know where I can find all the data that I imported to elasticsearch through logstash? Where are they stored? I want to delete all indices but cant find them anywhere. When I try to delete them in Kibana, they are still there.
I just downloaded zip files from Elasticsearch, Logstash and Kibana and run in directly from the batch file. Did not use any installation.There is a folder data in the elasticsearch folder, i can see the indices , even if I delete them from there, they are still somewhere and taking so much disk space. Any solution for this? Im working on windows 10. </p>

答:
In your comment, you clarified that what you are deleting in Kibana is not actual data, but only the index patterns (that's what you have in "Saved Objects") - see Kibana documentation.

If you want to delete data from Kibana, you would need to go to the Dev Tools > Console page (see Kibana documentation | Console), and use the Delete index API to delete your indices. E.g., by running something like

```<code>DELETE <your_index>
</code>```

If you don't know the names of your indices, you can run first the following command in the Dev Tools > Console:

```<code>GET _cat/indices
</code>```

Title: Delete all indices in elasticsearch

Body:
In your comment, you clarified that what you are deleting in Kibana is not actual data, but only the index patterns (that's what you have in "Saved Objects") - see Kibana documentation.

If you want to delete data from Kibana, you would need to go to the Dev Tools > Console page (see Kibana documentation | Console), and use the Delete index API to delete your indices. E.g., by running something like

DELETE <your_index>

If you don't know the names of your indices, you can run first the following command in the Dev Tools > Console:

GET _cat/indices


问:
Why do I need to do a "pip install" after "git clone.."?
I am following a (my company's internal) guide to installing some custom libraries from Bitbucket. I am instructed to do on the command line:

```<code># Install custom libraries.
git clone ssh://git@bitbucket.company.net:{number}/~js/company-libraries /tmp/company-libraries
</code>```

When I do

```<code>ls /tmp/company-libraries
</code>```

I see that there is a README.md file and a directory called CompanyLibraries

I am then instructed to do

```<code>sudo -H pip3 install /tmp/company-libraries/CompanyLibraries
</code>```

My question is that after doing "git clone.." why do we then need to do "pip3 install.."? What is pip doing in this case? The CompanyLibraries directory exists so I am unsure why we need to install again?

I have never used git and this guide doesn't assume any knowledge in git - it just wants me to copy and paste the commands.

答: "git clone" downloads the files, I guess they want you to install the libraries not just coping it to your machine because pip3 will install the libs where python3 is able to find them.</p>

Body:
I am following a (my company's internal) guide to installing some custom libraries from Bitbucket. I am instructed to do on the command line:

# Install custom libraries.
git clone ssh://git@bitbucket.company.net:{number}/~js/company-libraries /tmp/company-libraries

When I do

ls /tmp/company-libraries

I see that there is a README.md file and a directory called CompanyLibraries

I am then instructed to do

sudo -H pip3 install /tmp/company-libraries/CompanyLibraries

My question is that after doing "git clone.." why do we then need to do "pip3 install.."? What is pip doing in this case? The CompanyLibraries directory exists so I am unsure why we need to install again?

I have never used git and this guide doesn't assume any knowledge in git - it just wants me to copy and paste the commands.


问:
Compare the colnames within two lists of data.frames?
I am using a function that drops various columns from each data.frame in a list when those variables do not meet certain criteria, and I would like a convenient way to see which columns have been dropped. The real-world data.frames will have 1000s of varied colnames, with some overlap in those names.

It this simplified example, I would like to get a list that shows the variables of each data.frame that exist in list1 but which are absent in list2.

Input lists

```<code>> list1
$A
  a b
1 2 3
$B
  c d e
1 9 8 1
$C
  f g
1 6 7

> list2
$A
  a
1 2
$B
  c d
1 9 8
$C
  g
1 7
</code>```

Desired output

I'd like to keep the list structure, so that I see which columns were dropped from each data.frame.

```<code>$A
  b
1 3
$B
  e
1 1
$C
  f
1 6
</code>```

My attempts

I've looked on SO, but have only found solutions that pertain to comparing data.frames. Keep in mind the names of the list elements (here A, B and C) will always be the same in the lists. My idea has been to use setdiff , or setdiff with mapply, but my tinkering has not been fruitful. What can be done?

```<code>## sample data
list1 <- list(A=data.frame(a=2, b=3), B=data.frame(c=9,d=8,e=1), C=data.frame(f= 6,g=7))
list2 <- list(A=data.frame(a=2), B=data.frame(c=9,d=8), C=data.frame(g=7))
desired_output <- list(A=data.frame(b=3), B=data.frame(e=1), C=data.frame(f= 6))

## attempts

# gives List 1
setdiff(list1, list2)

# gives 'Error: not compatible: Cols in x but not y: `b`.'
mapply(setdiff, x = list1, y = list2)

# gives 'Error in list1[[i]] : recursive indexing failed at level 3'
mapply(setdiff, x = colnames(list1[[i]]), y = colnames(list2[[i]]))

# gives 'list()'
mapply(setdiff, x = colnames(list1[i]), y = colnames(list2[i]))

# Gives 'Error in list1[colnams] : invalid subscript type 'list''
colnams <- list()
for(i in seq_along(list1)){
   colnams[i] <- !colnames(list1[[i]]) %in% colnames(list2[[i]])
}
list1[colnams]
</code>```

答:
You can use lapply to extract the names and setdiff to get those not in the other list. No need that the list are sorted.

```<code>x <- lapply(list1, names)
y <- lapply(list2, names)
lapply(setNames(names(x), names(x)), function(i) list1[[i]][setdiff(x[[i]], y[[i]])])
#$A
#  b
#1 3
#
#$B
#  e
#1 1
#
#$C
#  f
#1 6
</code>```

Body:
I am using a function that drops various columns from each data.frame in a list when those variables do not meet certain criteria, and I would like a convenient way to see which columns have been dropped. The real-world data.frames will have 1000s of varied colnames, with some overlap in those names.

It this simplified example, I would like to get a list that shows the variables of each data.frame that exist in list1 but which are absent in list2.

Input lists

> list1
$A
  a b
1 2 3
$B
  c d e
1 9 8 1
$C
  f g
1 6 7

> list2
$A
  a
1 2
$B
  c d
1 9 8
$C
  g
1 7

Desired output

I'd like to keep the list structure, so that I see which columns were dropped from each data.frame.

$A
  b
1 3
$B
  e
1 1
$C
  f
1 6

My attempts

I've looked on SO, but have only found solutions that pertain to comparing data.frames. Keep in mind the names of the list elements (here A, B and C) will always be the same in the lists. My idea has been to use setdiff , or setdiff with mapply, but my tinkering has not been fruitful. What can be done?

## sample data
list1 <- list(A=data.frame(a=2, b=3), B=data.frame(c=9,d=8,e=1), C=data.frame(f= 6,g=7))
list2 <- list(A=data.frame(a=2), B=data.frame(c=9,d=8), C=data.frame(g=7))
desired_output <- list(A=data.frame(b=3), B=data.frame(e=1), C=data.frame(f= 6))

## attempts

# gives List 1
setdiff(list1, list2)

# gives 'Error: not compatible: Cols in x but not y: `b`.'
mapply(setdiff, x = list1, y = list2)

# gives 'Error in list1[[i]] : recursive indexing failed at level 3'
mapply(setdiff, x = colnames(list1[[i]]), y = colnames(list2[[i]]))

# gives 'list()'
mapply(setdiff, x = colnames(list1[i]), y = colnames(list2[i]))

# Gives 'Error in list1[colnams] : invalid subscript type 'list''
colnams <- list()
for(i in seq_along(list1)){
   colnams[i] <- !colnames(list1[[i]]) %in% colnames(list2[[i]])
}
list1[colnams]

Body:
You can use lapply to extract the names and setdiff to get those not in the other list. No need that the list are sorted.

x <- lapply(list1, names)
y <- lapply(list2, names)
lapply(setNames(names(x), names(x)), function(i) list1[[i]][setdiff(x[[i]], y[[i]])])
#$A
#  b
#1 3
#
#$B
#  e
#1 1
#
#$C
#  f
#1 6


问:
Simulating touch events on a PC browser
I am developing an HTML application for the iPad. As such it utilizes touch events and webkit-CSS animations.

Up until now I have used chrome as my debugging environment because of it's awesome developer mode.

What I would like is to be able to debug my Html/JavaScript using Google-Chrome's debugger on my PC while simulating touch events with my mouse.

My site does not have any multi-touch events and no mouse events (no mouse on iPad).

I am not actually interested in seeing the applications layout, but more in debugging its behavior.

Is there some plugin to get mouse events translated into touch events on a desktop browser?

答:
We use this script: http://code.google.com/p/jquery-ui-for-ipad-and-iphone/
It will allow all mouse events in your application to be triggered by touch events instead. So, since we already had a web application that used right-clicking, drag-n-drop etc. it allowed us to perform all of the same functionality with touch.

I know it's almost the reverse of the simulation you were looking for (you will have to script your application to primarily be used by a mouse) but I hope it helps anyway.

Title: Simulating touch events on a PC browser