Skip to content

Commit

Permalink
Improve ReflectionUtils (#42)
Browse files Browse the repository at this point in the history
* Use system dependant path separator

* Properly close file handles

* Update src/main/java/com/freya02/botcommands/internal/utils/ReflectionUtils.java

* Update src/main/java/com/freya02/botcommands/internal/utils/ReflectionUtils.java

Co-authored-by: freya02 <[email protected]>
  • Loading branch information
oxkitsune and freya022 authored Aug 25, 2022
1 parent 566fe8f commit 00248f9
Showing 1 changed file with 20 additions and 19 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import java.nio.file.Path;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class ReflectionUtils {
private static final StackWalker walker = StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE);
Expand All @@ -34,7 +35,7 @@ public static Set<Class<?>> getPackageClasses(@NotNull String packageName, int m
final String packagePath = packageName.replace('.', File.separatorChar);

final String classPath = System.getProperty("java.class.path");
for (String strPath : classPath.split(";")) {
for (String strPath : classPath.split(File.pathSeparator)) {
final Path jarPath = Path.of(strPath);

final Path walkRoot;
Expand All @@ -50,24 +51,24 @@ public static Set<Class<?>> getPackageClasses(@NotNull String packageName, int m
continue;
}

Files.walk(walkRoot, maxDepth)
.filter(Files::isRegularFile)
.filter(p -> IOUtils.getFileExtension(p).equals("class"))
.forEach(p -> {
// Change from a/b/c/d to c/d
final String relativePath = walkRoot.relativize(p)
.toString()
.replace(walkRoot.getFileSystem().getSeparator(), ".");

//Remove .class suffix and add package prefix
final String result = packageName + "." + relativePath.substring(0, relativePath.length() - 6);

try {
classes.add(Class.forName(result, false, Utils.class.getClassLoader()));
} catch (ClassNotFoundException e) {
LOGGER.error("Unable to load class '{}' in class path '{}', isJAR = {}, filesystem: {}", result, strPath, isJar, walkRoot.getFileSystem(), e);
}
});
try (Stream<Path> stream = Files.walk(walkRoot, maxDepth)) {
stream.filter(Files::isRegularFile)
.filter(p -> IOUtils.getFileExtension(p).equals("class"))
.forEach(p -> {
// Change from a/b/c/d to c/d
final String relativePath = walkRoot.relativize(p)
.toString()
.replace(walkRoot.getFileSystem().getSeparator(), ".");

//Remove .class suffix and add package prefix
final String result = packageName + "." + relativePath.substring(0, relativePath.length() - 6);
try {
classes.add(Class.forName(result, false, Utils.class.getClassLoader()));
} catch (ClassNotFoundException e) {
LOGGER.error("Unable to load class '{}' in class path '{}', isJAR = {}, filesystem: {}", result, strPath, isJar, walkRoot.getFileSystem(), e);
}
});
}
}

return classes;
Expand Down

0 comments on commit 00248f9

Please sign in to comment.