Skip to content

Commit 1b78afe

Browse files
committed
Properly identify event-related ClassCastExceptions on JDK 11
Issue: SPR-17093 (cherry picked from commit e458777)
1 parent 001cecd commit 1b78afe

File tree

1 file changed

+10
-6
lines changed

1 file changed

+10
-6
lines changed

spring-context/src/main/java/org/springframework/context/event/SimpleApplicationEventMulticaster.java

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -173,7 +173,7 @@ private void doInvokeListener(ApplicationListener listener, ApplicationEvent eve
173173
}
174174
catch (ClassCastException ex) {
175175
String msg = ex.getMessage();
176-
if (msg == null || matchesClassCastMessage(msg, event.getClass().getName())) {
176+
if (msg == null || matchesClassCastMessage(msg, event.getClass())) {
177177
// Possibly a lambda-defined listener which we could not resolve the generic event type for
178178
// -> let's suppress the exception and just log a debug message.
179179
Log logger = LogFactory.getLog(getClass());
@@ -187,14 +187,18 @@ private void doInvokeListener(ApplicationListener listener, ApplicationEvent eve
187187
}
188188
}
189189

190-
private boolean matchesClassCastMessage(String classCastMessage, String eventClassName) {
191-
// On Java 8, the message simply starts with the class name: "java.lang.String cannot be cast..."
192-
if (classCastMessage.startsWith(eventClassName)) {
190+
private boolean matchesClassCastMessage(String classCastMessage, Class<?> eventClass) {
191+
// On Java 8, the message starts with the class name: "java.lang.String cannot be cast..."
192+
if (classCastMessage.startsWith(eventClass.getName())) {
193193
return true;
194194
}
195-
// On Java 9, the message contains the module name: "java.base/java.lang.String cannot be cast..."
195+
// On Java 11, the message starts with "class ..." a.k.a. Class.toString()
196+
if (classCastMessage.startsWith(eventClass.toString())) {
197+
return true;
198+
}
199+
// On Java 9, the message used to contain the module name: "java.base/java.lang.String cannot be cast..."
196200
int moduleSeparatorIndex = classCastMessage.indexOf('/');
197-
if (moduleSeparatorIndex != -1 && classCastMessage.startsWith(eventClassName, moduleSeparatorIndex + 1)) {
201+
if (moduleSeparatorIndex != -1 && classCastMessage.startsWith(eventClass.getName(), moduleSeparatorIndex + 1)) {
198202
return true;
199203
}
200204
// Assuming an unrelated class cast failure...

0 commit comments

Comments
 (0)