Aritro Sen
Aritro Sen

Reputation: 357

Find all the classes inside a package in Java without reflection

I am trying to find all the classes defined inside a package. I have tried this code -

public static File[] getPackageContent(String packageName) throws IOException{
    ArrayList<File> list = new ArrayList<File>();
    Enumeration<URL> urls = Thread.currentThread().getContextClassLoader().getResources(packageName);
    while (urls.hasMoreElements()) {
        URL url = urls.nextElement();
        File dir = new File(url.getFile());
        for (File f : dir.listFiles()) {
            list.add(f);
        }
    }
    return list.toArray(new File[]{});

Now here is the thing - if the String packageName does not contain "." character, it returns me all the names of the classes which I want exactly. But suppose if the packageName contains "." character it does not return anything.

Why is that? If possible how can I find all the classes inside a package where the package name does have a "." character in it?

Upvotes: 1

Views: 534

Answers (1)

StackFlowed
StackFlowed

Reputation: 6816

You could use Reflections:

    private Class<?>[] scanForTasks(String packageStr) {
        Reflections reflections = new Reflections((new ConfigurationBuilder()).setScanners(new Scanner[]{new SubTypesScanner(), new TypeAnnotationsScanner()}).setUrls(ClasspathHelper.forPackage(packageStr, new ClassLoader[0])).filterInputsBy((new FilterBuilder()).includePackage(packageStr)));
        Set classes = reflections.getTypesAnnotatedWith(Task.class);
        Class[] taskArray = (Class[])classes.toArray(new Class[classes.size()]);
        return taskArray;
    }
}

Upvotes: 1

Related Questions