-2

I would like to search the runtime classpath to find all classes with a simple name that matches some regex.

Example:
Say I have Some.jar on my classpath and that jar contains a class called MyCoolClass.class. I would like some way of finding all classes that contains the word "Cool" like the one above and perhaps several others.

Also, I would like to get either the Class or the fully qualified class name (such that I can call Class.forName).

Hervian
  • 1,066
  • 1
  • 12
  • 20
  • Take into account that a running jvm might have more classes loaded than are on the classpath, because it might have dynamically created classes at runtime or it might have loaded them dynamically from a remote location. – SpaceTrucker Aug 19 '22 at 13:22

2 Answers2

0

I managed to solve this using the ClassGraph library:

// List<URL> myClassPath = ... //get classpath. I got mine from the Maven context since I was developing a Mojo
List<String> foundTypes;
  try (ScanResult scanResult = new ClassGraph().enableClassInfo().overrideClasspath(myClassPath).scan()) {
    foundTypes = scanResult.getAllClasses().getNames().stream().filter(e -> e.contains("Cool")).collect(Collectors.toList());
  }

  foundTypes.forEach(e -> System.out.println(e));

Outputs the fully qualified class names.

Alternative libraries thay may (or may not) also be able to achieve this:

Hervian
  • 1,066
  • 1
  • 12
  • 20
0

Using Reflextions

Reflections reflections = new Reflections( "com.my.package", SubTypes.filterResultsBy( s -> true));
Set<Class<?>> subTypes = reflections.get( SubTypes.of( Object.class).asClass());
  subTypes.stream()
     .filter( t -> t.getName().contains( "Cool"))
     .forEach( t -> { 
        log.info( "Class: {}", t.getName());
     });
Gerard
  • 21
  • 5