【问题标题】:Getting method with Generic Types within signature using Reflection使用反射在签名中获取具有通用类型的方法
【发布时间】:2022-11-10 17:02:56
【问题描述】:

我想使用 Reflection 调用此方法,但对使用 getDeclaredMethod() 获取该方法有点困惑,这将如何完成?

 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);
    }
}

【问题讨论】:

标签: java reflection


【解决方案1】:

尝试这个: .getDeclaredMethod("registerServiceClass", Class.class, Object.class) ;

在运行时不可能在方法范围内推断泛型类型,因为编译器会删除此信息

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-06
    相关资源
    最近更新 更多