我一直在研究Spring中的事件侦听器,并遇到了ApplicationListener接口。哪个可以使用泛型,例如:

public class CStopEventHandler
   implements ApplicationListener<ContextStoppedEvent>{

   public void onApplicationEvent(ContextStoppedEvent event) {
      System.out.println("ContextStoppedEvent Received");
   }
}


当在运行时擦除通用类型时,事件调度程序如何在运行时知道ApplicationListener的类型?是否使用反射或类似方法检查方法签名?

最佳答案

你是对的。 Spring(当然还有整个Java)在运行时使用Reflection来从提供的类中确定generic type

在我们的案例中,应用程序上下文扫描Bean的ApplicationListener实现,并将它们全部存储在列表中。

引发ApplicationEvent时,将处理ApplicationListener的列表以确定特定事件类型的侦听器,并将它们存储在缓存中以供将来优化。

但是在此之前,您的ApplicationListener<?>被包装到GenericApplicationListenerAdapter,以使用提供的supportsEventType中的通用类型调用其ApplicationListener

我想您想知道这种方法:

static Class<?> resolveDeclaredEventType(Class<?> listenerType) {
        return GenericTypeResolver.resolveTypeArgument(listenerType, ApplicationListener.class);
    }


当您需要在运行时知道GenericTypeResolver时,可以在任何地方使用代码中的generic type

07-23 08:34