4

I did search the solution for finding all subclasses for a given class and I saw this thread

As far as I know, there are some tools to do that such as Reflections, using ClassPathScanningCandidateComponentProvider in Spring framework, or extcos. But after trying them all, seems none of them works for a given class in jdk (List, Map, Number, ...).

I looked into their source code, see how they work, I think the reason is because they need to get the package in which we look for the subclasses as resource, and the function classloader.getResource(String name), always returns null for a package name in jdk.

So, why classloader.getResource(String name) returns null for a package name in jdk? and does anyone know a solution to get subclasses that works for jdk as well?

Community
  • 1
  • 1
  • 1
    Can you add an example what resource was not found? If you run `System.out.println(getClass().getClassLoader().getResource("java/lang/String.class"));` you will get an url. – Cfx Jan 20 '15 at 09:31
  • This is what I tried : ClassLoader.getSystemClassLoader().getResource("java/util"); It returns value if I get resource for a path of another package not in jdk – user4469150 Jan 20 '15 at 09:33
  • 1
    As the post said,you have to scan all the classes in the jdk to get all the subclasses – snow8261 Jan 20 '15 at 09:35

1 Answers1

1

Why do you not try one of the solutions from your link?

Find below a simple example using https://github.com/ronmamo/reflections.git.

After having a look in the test classes this example was straight forward.

Reflections reflections = new Reflections(new ConfigurationBuilder()
        .setUrls(Arrays.asList(ClasspathHelper.forClass(List.class))));

Set<Class<? extends List>> subTypes = reflections.getSubTypesOf(List.class);
for (Class c : subTypes) {
    System.out.println("subType: " + c.getCanonicalName());
}
SubOptimal
  • 22,518
  • 3
  • 53
  • 69
  • Thanks a lot, it works perfectly. I did try the Reflections, but not using the configuration, and only focus on extcos for better performance :) – user4469150 Jan 20 '15 at 10:15