TinyOS TinyOS - 4 years ago 160
Java Question

How can i do to get all class of a given package with guava

I am working on a maven project and I added to my pom.xml file the guava dependency and the dependency of an other project. I want to get all class of a given package of that project which I have added to my pom as a dependency.
So I tried with this :

public void getClassOfPackage() {

final ClassLoader loader = Thread.currentThread()
.getContextClassLoader();
try {
for (final ClassPath.ClassInfo info : ClassPath.from(loader)
.getTopLevelClasses()) {

System.out.println(info.getSimpleName());

}
} catch (IOException e) {
e.printStackTrace();
}

}

public static void main(String[] args) {
new TestMain().getClassOfPackage();
}


And I know that is wrong because it gives that in console:

HierarchicalConfigurationConverter
HierarchicalConfigurationXMLReader
HierarchicalINIConfiguration
SubsetConfiguration
SystemConfiguration...


I don't know where I can specify the project where I am talking about and how I can just pass the package name and it gives me all class which it contains.

Answer Source

This is why you're seeing it print out sun.misc.Launcher$AppClassLoader:

} else {
     System.out.println(loader.getClass().getName());
}

Every class on your classpath that isn't in your package is causing your program to print out the name of the ClassLoader implementation class, which you probably don't want.

Also, while info.getName().startsWith("org.mypackage") should work, it might be preferable to write info.getPackageName().equals("org.mypackage") (or startsWith if you want to include subpackages too).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download