lundi 16 avril 2018

Why does not this reflection work?

In a java module of my android application, I am trying to get class names in a package with the following (copied from java examples):

public class Utils
{
    public static Class[] getClasses(String... packageNames) throws ClassNotFoundException, IOException
    {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        ArrayList<Class> classes = new ArrayList<Class>();

        for (String packageName : packageNames)
        {
            String path = packageName.replace('.', '/');
            Enumeration<URL> resources = classLoader.getResources(path);
            List<File> dirs = new ArrayList<File>();
            while (resources.hasMoreElements())
            {
                URL resource = resources.nextElement();
                dirs.add(new File(resource.getFile()));
            }

            for (File directory : dirs)
            {
                classes.addAll(findClasses(directory, packageName));
            }
        }

        return classes.toArray(new Class[classes.size()]);
    }

    private static List<Class> findClasses(File directory, String packageName) throws ClassNotFoundException
    {
        List<Class> classes = new ArrayList<Class>();
        if (!directory.exists())
        {
            return classes;
        }
        File[] files = directory.listFiles();
        for (File file : files)
        {
            if (file.isDirectory())
            {
                assert !file.getName().contains(".");
                classes.addAll(findClasses(file, packageName + "." + file.getName()));
            }
            else if (file.getName().endsWith(".class"))
            {
                classes.add(Class.forName(packageName + '.' + file.getName().substring(0, file.getName().length() - 6)));
            }
        }
        return classes;
    }
}

From my module I am calling like this:

Class[] foundClasses = Utils.getClasses("com.my.module.package");

It worked in another java project, but it is not working here; no exception/error, just not returning the classes.

Any idea how to get around this? Please do not suggest solution using DexFile. I have already tried that and it works; but I need to build a module (jar) which should be working on both java and android.





Aucun commentaire:

Enregistrer un commentaire