BreakMe/src/main/java/io/gitlab/jfronny/breakme/ClassFinder.java

42 lines
1.7 KiB
Java

package io.gitlab.jfronny.breakme;
import net.fabricmc.loader.api.FabricLoader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
public class ClassFinder {
public static List<Class<?>> find(String packageName) throws NoSuchElementException, IOException {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
Path p = FabricLoader.getInstance()
.getModContainer(BreakMe.MOD_ID)
.orElseThrow(FileNotFoundException::new)
.findPath(".")
.orElseThrow(FileNotFoundException::new)
.toAbsolutePath();
return findInternal(p, p.resolve(packageName.replace('.', '/')), classLoader);
}
private static List<Class<?>> findInternal(Path rootPath, Path path, ClassLoader classLoader) throws IOException {
List<Class<?>> result = new ArrayList<>();
Files.list(path).forEach(s -> {
try {
if (Files.isDirectory(s)) {
result.addAll(findInternal(rootPath, s, classLoader));
} else if (s.getFileName().toString().endsWith(".class")) {
String p = rootPath.relativize(s).toString().replace('/', '.');
result.add(classLoader.loadClass(p.substring(0, p.length() - ".class".length())));
}
} catch (Throwable e) {
BreakMe.LOGGER.error("Could not scan classpath for crash method", e);
}
});
return result;
}
}