1

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?

JAL
  • 41,701
  • 23
  • 172
  • 300
Aritro Sen
  • 357
  • 7
  • 14

1 Answers1

1

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;
    }
}
StackFlowed
  • 6,664
  • 1
  • 29
  • 45
  • 1
    Since the question has been edited to ask about doing this without reflection, your answer isn't applicable anymore. – azurefrog Dec 23 '15 at 18:47