kiafumi/src/main/java/moe/oko/Kiafumi/command/CommandRegistrar.java

60 lines
2.3 KiB
Java
Raw Normal View History

package moe.oko.Kiafumi.command;
import com.google.common.reflect.ClassPath;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import static moe.oko.Kiafumi.Kiafumi.error;
import static moe.oko.Kiafumi.Kiafumi.info;
public class CommandRegistrar {
public Set<Class> findAllClassesContaining(String packageName) {
try {
return ClassPath.from(ClassLoader.getSystemClassLoader())
.getAllClasses()
.stream()
.filter(clazz -> clazz.getPackageName()
.contains(packageName))
.map(clazz -> clazz.load())
.collect(Collectors.toSet());
} catch (Exception ex) {
error("Failed to load classes containing " + packageName + ", check stack.");
ex.printStackTrace();
return null;
}
}
public List<CommandClass> getCommandClasses() {
try {
Set<Class> classes = findAllClassesContaining("moe.oko.Kiafumi.command");
List<CommandClass> commands = new ArrayList<>();
info("Found " + classes.size() + " classes containing moe.oko.Kiafumi.command in package class.");
for (Class clazz : classes) {
for (Constructor cnstr : clazz.getConstructors()) {
try {
var obj = cnstr.newInstance(); //making an attempt.
if (obj instanceof CommandClass) {
info("Instance found (" + cnstr.getName() + ")! Registering.");
commands.add((CommandClass) obj);
}
} catch (InstantiationException ex) {
//Ignore, this is just us trying to load the CommandClass abstract class. We ignore it.
}
}
}
return commands;
} catch (IllegalAccessException | InvocationTargetException exception) {
//Now we don't ignore, this is a core issue.
exception.printStackTrace();
error("fucky wucky in class loading.");
return null;
}
}
}