4

I am looking to print out all classes in all of the packages in my Java project. For example, say the project contained

Package1.Class1
Package1.Class2
Package1.Class3
Package2.Class1
Package2.Class2

I would want to print out all of these packages and classes. Using the following code, I am able to list them, but only when I reference in the manner of Package.Class c = new Package.Class();

Here is the code I am trying to use:

Package[] pa = Package.getPackages();
for (int i = 0; i < pa.length; i++) {
    Package p = pa[i];
    System.out.print("\"" + p.getName() + "\", ");
}

Any thoughts on how I can do this?

Thanks all

Pshemo
  • 122,468
  • 25
  • 185
  • 269
user1928436
  • 165
  • 9
  • 1
    *When* do you need it? At runtime or before packaging (let's say at compile time)? – Raffaele Jan 01 '13 at 19:40
  • 2
    duplicated? http://stackoverflow.com/questions/520328/can-you-find-all-classes-in-a-package-using-reflection – Kent Jan 01 '13 at 19:43

2 Answers2

3

There's no easy way due to the dynamic nature of classloaders.

However you could look at the reflections library : http://code.google.com/p/reflections/

Which will allow you to lookup the classes in the current classpath.

With that library you can try something like this:

 Reflections reflects = new Reflections("my.project.prefix");

 Set<Class<? extends Object>> allClasses = 
 reflects.getSubTypesOf(Object.class);
Mark
  • 2,423
  • 4
  • 24
  • 40
2

Go with reflections, or parse the classpath, splitting it into individual folders and / or jar files, walking each of them and listing the packages. But that's way more complicated than using the reflections library.

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
  • @Kent I'd use the reflections library myself, but I just wanted to make clear that there are alternatives. Spring's classpath scanning technologies also come to mind. – Sean Patrick Floyd Jan 03 '13 at 09:30