mercredi 10 janvier 2018

How to check interface generic type at runtime

I am trying to get the Class<?> for the generic type used by an interface at runtime.

So if I have the following

Class <T> A implements B<T>{...}

Interface <T> B extends C<Z>, D<T>{...}

A temp = new A<MyClass>();

I want to be able to get the Class<?> of the first (or later) generic of B, C, or D, given the instance temp.

Right now I have this, but it only works for interfaces this instance's class directly implements. I want to modify it to work regardless of how this instance inherited the target interface.

/**
 * Finds this instances implementation of the interfaceClass, and returns
 * the associated generic type
 *
 * @param instance
 *            the instance to extract from
 * @param interfaceClass
 *            The class this instance implements
 * @param paramIndex
 *            Index of the generic class to get the class of
 * @return The class of the generic type
 * @throws ClassNotFoundException
 */
public static <T> Class<?> ParameterizedClass(final T instance, final Class<T> interfaceClass, final int paramIndex)
        throws ClassNotFoundException {
    final Type[] sooper = instance.getClass().getGenericInterfaces();
    for (final Type t : sooper) {
        if (!(t instanceof ParameterizedType)) {
            continue;
        }

        final ParameterizedType type = ((ParameterizedType) t);
        if (type.getRawType().getTypeName().equals(interfaceClass.getTypeName())) {
            return Class.forName(type.getActualTypeArguments()[paramIndex].getTypeName());
        }
    }

    return null;
}





Aucun commentaire:

Enregistrer un commentaire