Search code examples
javareflection

Getting method with Generic Types within signature using Reflection


I would like to invoke this method using Reflection but am a bit confused with getting the method with getDeclaredMethod(), how would this be done?

 private static <T> void registerServiceClass(final Class<T> service, final T instance) {
        Collection<Class<?>> serviceClasses = SERVICE_MAP.get(service);
        if (null == serviceClasses) {
            serviceClasses = new LinkedHashSet<>();
        }
        serviceClasses.add(instance.getClass());
        SERVICE_MAP.put(service, serviceClasses);
    }
}

Solution

  • Try this: .getDeclaredMethod("registerServiceClass", Class.class, Object.class) ;

    It is impossible to infer generic types within method scope at runtime, as this information is erased by the compiler

    https://docs.oracle.com/javase/tutorial/java/generics/erasure.html