Get all classes under a packagejava/reflection/get-all-classes-under-packageUse guava to get all classes under a package without loading it
1import com.google.common.reflect.ClassPath;
2
3// package filter
4var packageName = "com.trychen.index";
5
6// get all class info
7var classInfos = ClassPath.from(loader)
8 .getAllClasses()
9 .stream()
10 .filter(clazz -> clazz.getPackageName().startsWith(packageName))
11 .collect(Collectors.toSet());
12
13// load into class (exception may throw)
14var classes = classInfos.stream()
15 .map(ClassPath.ClassInfo::load)
16 .collect(Collectors.toSet());Disclaimer
The code snippet is provided for reference and learning purposes only. Users should use it at their own risk. I, along with the related developers, shall not be held responsible for any direct or indirect losses caused by the use of this code snippet, including but not limited to data loss, computer malfunctions, program errors, etc.