ClassLoader.getResource
can throw IllegalArgumentException
if a malformed URL is provided to it.
According to its javadoc, resolveURL
should return null if not resolvable, so catch the IllegalArgumentException
and return null.
Example stack trace produced by new org.springframework.core.io.DefaultResourceLoader().getResource("C:/users/candrews/example").exists()
java.lang.IllegalArgumentException: name
at java.base/jdk.internal.loader.URLClassPath$Loader.findResource(URLClassPath.java:600)
at java.base/jdk.internal.loader.URLClassPath.findResource(URLClassPath.java:291)
at java.base/java.net.URLClassLoader$2.run(URLClassLoader.java:655)
at java.base/java.net.URLClassLoader$2.run(URLClassLoader.java:653)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at java.base/java.net.URLClassLoader.findResource(URLClassLoader.java:652)
at org.springframework.boot.loader.LaunchedURLClassLoader.findResource(LaunchedURLClassLoader.java:100)
at java.base/java.lang.ClassLoader.getResource(ClassLoader.java:1401)
at org.springframework.core.io.ClassPathResource.resolveURL(ClassPathResource.java:155)
at org.springframework.core.io.ClassPathResource.exists(ClassPathResource.java:142)
Comment From: candrews
I believe that this issue is caused by a bug in Java. Quoting the javadoc of java.lang.ClassLoader.getResource(String):
Returns: URL object for reading the resource; null if the resource could not be found, a URL could not be constructed to locate the resource, the resource is in a package that is not opened unconditionally, or access to the resource is denied by the security manager.
In this case, "a URL could not be constructed to locate the resource" so null should be returned. But that's not what's happening.
I've reported this issue at https://bugreport.java.com/ (internal review ID : 9069151) and https://github.com/openjdk/jdk/pull/2662