views:

99

answers:

4

Possible Duplicate:
Can you find all classes in a package using reflection?

suppose I've a package name as string:

String pkgName = "com.forat.web.servlets";

How to know the types in this package?

+3  A: 

That's not possible in full generality. If your classes are stored in a directory or JAR file, you can look at its contents, but the classloader mechanism is so flexible that the question "what classes are in this package" simply does not make sense - it's possible to write a classloader that returns a class for any classname you ask for.

Michael Borgwardt
Oh, come on, it does make sense, even it is not possible to always answer the question.
doublep
+1  A: 

Can you provide some more details, like what kind of environment? A standalone app, a webapp in a application server. Where are the classes loaded from? JARs, separate files on a file system, a network class loader etc.

There is no simple answer, simply because there is no simple definition of a package. A package can be spread over multiple jars, multiple class loaders, and in the case of network class loaders, the classes exist on another machine.

Finally, do you want to just consider classes that are loaded in the VM or all classes present on the classpath?

EDIT: See also this related question.

mdma
A: 

These two answers explain methods that should cover many practical problems:

erickson
A: 

f you have a .jar file that you want to get the .class files from you can use the following:

  • java.util.jar.JarEntry

  • java.net.JarURLConnection created via java.​net.​URL.

  • The URL in this case is the package name in this case is: com.forat.web.servlets

Example

(NOTE: ignores exception handling)

// Get the "things" that are in the .jar
Enumeration<JarEntry> jarEntries = 
    ((JarURLConnection)urlToJar.openConnection()).getJarFile().entries();
while(jarEntries.hasMoreElements())
{
    String entry = jarEntries.nextElement().getName();

    if (entry.endsWith(".class"))
    {
        // TODO: Remove "." from result.
    // Here is the first of the classes in the .servlets location
        Class.forName(entry);
    }
}

bn