mercredi 26 juillet 2023

How could I run the constructor of all the classes in a package without knowing the names of all of the classes?

I want to make a class that would run the constructor of each class in the package, excluding itself of course. So I would be able to add another class to the package and the constructor of the class would be run without having to go and explicitly call it in the main class. Its for a minecraft plugin so its being compiled into a jar and run that way chat gpt said that made some kind of difference.

I've tried to get the package name and use that to get a path which would look for all of the files using a class loader. I'm able to get a list of the classes in a different project but not in the plugin.

public static List<Class<?>> getClassList() {
        List<Class<?>> classList = new ArrayList<>();
        String packageName=Loader.class.getPackage().getName();
        String packagePath = packageName.replace('.', '/');

        try {
            java.lang.ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
            if (classLoader == null) {
                throw new ClassNotFoundException("Unable to get class loader.");
            }

            // Get all resources (files and directories) in the package directory
            java.util.Enumeration<java.net.URL> resources = classLoader.getResources(packagePath);
            while (resources.hasMoreElements()) {
                java.net.URL resource = resources.nextElement();
                if (resource.getProtocol().equals("file")) {
                    // If the resource is a file, get class objects
                    getClassObjectsFromFile(packageName, resource.getPath(), classList);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return classList;
    }

    private static void getClassObjectsFromFile(String packageName, String filePath, List<Class<?>> classList)
            throws ClassNotFoundException {
        java.io.File directory = new java.io.File(filePath);
        if (directory.exists()) {
            java.io.File[] files = directory.listFiles();
            if (files != null) {
                for (java.io.File file : files) {
                    if (file.isFile() && file.getName().endsWith(".class")) {
                        String className = packageName + '.' + file.getName().substring(0, file.getName().length() - 6);
                        Class<?> clazz = Class.forName(className);
                        classList.add(clazz);
                    }
                }
            }
        }
    }

Thanks





Aucun commentaire:

Enregistrer un commentaire