Add ResolvableTypeProvider
Provide a mean to detect the actual ResolvableType based on a instance as a counter measure to type erasure. Upgrade the event infrastructure to detect if the event (or the payload) implements such interface. When this is the case, the return value of `getResolvableType` is used to validate its generic type against the method signature of the listener. Issue: SPR-13069
This commit is contained in:
@@ -16,6 +16,8 @@
|
||||
|
||||
package org.springframework.context;
|
||||
|
||||
import org.springframework.core.ResolvableType;
|
||||
import org.springframework.core.ResolvableTypeProvider;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
@@ -28,7 +30,7 @@ import org.springframework.util.Assert;
|
||||
* @param <T> the payload type of the event
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public class PayloadApplicationEvent<T> extends ApplicationEvent {
|
||||
public class PayloadApplicationEvent<T> extends ApplicationEvent implements ResolvableTypeProvider {
|
||||
|
||||
private final T payload;
|
||||
|
||||
@@ -44,6 +46,11 @@ public class PayloadApplicationEvent<T> extends ApplicationEvent {
|
||||
this.payload = payload;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResolvableType getResolvableType() {
|
||||
return ResolvableType.forClassWithGenerics(getClass(),
|
||||
ResolvableType.forInstance(getPayload()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the payload of the event.
|
||||
|
||||
@@ -124,10 +124,11 @@ public class ApplicationListenerMethodAdapter implements GenericApplicationListe
|
||||
protected Object[] resolveArguments(ApplicationEvent event) {
|
||||
if (!ApplicationEvent.class.isAssignableFrom(this.declaredEventType.getRawClass())
|
||||
&& event instanceof PayloadApplicationEvent) {
|
||||
@SuppressWarnings("rawtypes")
|
||||
Object payload = ((PayloadApplicationEvent) event).getPayload();
|
||||
if (this.declaredEventType.isAssignableFrom(ResolvableType.forClass(payload.getClass()))) {
|
||||
return new Object[] {payload};
|
||||
PayloadApplicationEvent<?> payloadEvent = (PayloadApplicationEvent<?>) event;
|
||||
ResolvableType payloadType = payloadEvent.getResolvableType()
|
||||
.as(PayloadApplicationEvent.class).getGeneric(0);
|
||||
if (this.declaredEventType.isAssignableFrom(payloadType)) {
|
||||
return new Object[] {payloadEvent.getPayload()};
|
||||
}
|
||||
}
|
||||
else {
|
||||
|
||||
@@ -139,7 +139,7 @@ public class SimpleApplicationEventMulticaster extends AbstractApplicationEventM
|
||||
}
|
||||
|
||||
private ResolvableType resolveDefaultEventType(ApplicationEvent event) {
|
||||
return ResolvableType.forType(event.getClass());
|
||||
return ResolvableType.forInstance(event);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user