Monday, 6 September 2021

Finding out where your class comes from

Sometimes it happens that we're stuck in ClassPath hell. Which means that there's two conflicting dependencies, both putting the same class (but different!) on the classpath, and it's random which one will be first.

There's a way to find out.

public class ClassTest {
@Test
public void testClassResource() {
URL resource = getClass().getResource("/org/testng/annotations/Test.class");
assertThat(resource).isNotNull();
assertThat(resource.toString()).endsWith("/org/testng/testng/6.13.1/testng-6.13.1.jar!/org/testng/annotations/Test.class");
}
@Test
public void testClassloaderResource() {
URL resource = getClass().getClassLoader().getResource("org/testng/annotations/Test.class");
assertThat(resource).isNotNull();
assertThat(resource.toString()).endsWith("/org/testng/testng/6.13.1/testng-6.13.1.jar!/org/testng/annotations/Test.class");
}
}
view raw ClassTest.java hosted with ❤ by GitHub

References

GitHub - my Gists
https://gist.github.com/maartenl/00663f1d1dbaf4dd0792e864a9074e65