Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,11 @@ protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundE
return super.loadClass(name, true);
}
catch (ClassNotFoundException ex) {
return loadClassFromResource(name);
Class<?> loadedFromResource = loadClassFromResource(name);
if (loadedFromResource == null) {
throw ex;
}
return loadedFromResource;
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;

/**
* Tests for {@link ThrowawayClassLoader}.
Expand Down Expand Up @@ -56,6 +57,23 @@ public InputStream getResourceAsStream(String name) {
assertThat(closed).as("InputStream closed").isTrue();
}

@Test
void loadClassThrowsClassNotFoundExceptionWhenClassResourceIsMissing() {
// The grandparent resolves bootstrap classes only, so super.loadClass(...) fails,
// and the resource loader provides no class bytes. The fallback must then honor the
// ClassLoader.loadClass contract by reporting the failure instead of returning null.
ClassLoader resourceLoader = new ClassLoader(new ClassLoader(null) {}) {
@Override
public InputStream getResourceAsStream(String name) {
return null;
}
};
ThrowawayClassLoader classLoader = new ThrowawayClassLoader(resourceLoader);

assertThatExceptionOfType(ClassNotFoundException.class)
.isThrownBy(() -> classLoader.loadClass("com.example.MissingClass"));
}

private static byte[] classBytesOf(String className) throws IOException {
String resourceName = className.replace('.', '/') + ".class";
try (InputStream in = ThrowawayClassLoaderTests.class.getClassLoader().getResourceAsStream(resourceName)) {
Expand Down