How to get a list of classes of a given Package?

Hello everyone,

I'm wondering if it is possible to get all class names for a Package object or a package name. What I'm looking for looks something like this:

Package p;

String[] classNames = p.getClasses();

So that after that I could get Class objects of this Package:

Class class0 = Class.forName(classNames[0]);

Class class1 = ...

//etc

Thank you and best regards,

MenavitaTak

[442 byte] By [MenavitaTaka] at [2007-10-2 22:13:35]
# 1

Java loads its classes lazily. This means that if you write a class MyClass and put it in your classpath but never reference it at runtime, the class will never be loaded. This is why the java.lang.Package class doesn't have a getClasses() method. It could theoretically give you the classes it has loaded so far, but there may be more that need to be loaded later, so that wouldn't be much use. The only solution I can think of is to write a method that cruises the classpath looking for the folder structure of your package and sniffs all the classes in that structure. The TrueZip project may help you if you decide to do that because it would treat jars in the classpath just like directories. Good luck.

Updownquarka at 2007-7-14 1:30:26 > top of Java-index,Core,Core APIs...
# 2

> Hello everyone,

>

> I'm wondering if it is possible to get all class

> names for a Package object or a package name.

In general no.

Classes don't belong to a package. The only thing a package does is provide a name.

> What

> I'm looking for looks something like this:

>

> Package p;

> String[] classNames = p.getClasses();

>

If you search this site there is example code somewhere that demonstrates the following idea.

1. A given class has a classloader

2. That classloader provides a way to get the 'source' of a class.

3. One can use that source and parse it looking for other classes.

jschella at 2007-7-14 1:30:26 > top of Java-index,Core,Core APIs...