views:

254

answers:

7

Lets say I have a java package commands which contains classes that all inherit from ICommand can I get all of those classes somehow? I'm locking for something among the lines of:

Package p = Package.getPackage("commands");
Class<ICommand>[] c = p.getAllPackagedClasses(); //not real

Is something like that possible?

+1  A: 

Start with public Classloader.getResources(String name). Ask the classloader for a class corresponding to each name in the package you are interested. Repeat for all classloaders of relevance.

bmargulies
+1  A: 

Yes but its not the easiest thing to do. There are lots of issues with this. Not all of the classes are easy to find. Some classes could be in a: Jar, as a class file, over the network etc.

Take a look at this thread.

To make sure they were the ICommand type then you would have to use reflection to check for the inheriting class.

monksy
+2  A: 

Here is an utility method, using Spring.

Details about the pattern can be found here

    public static List<Class> listMatchingClasses(String matchPattern) throws IOException {
    List<Class> classes = new LinkedList<Class>();
    PathMatchingResourcePatternResolver scanner = new PathMatchingResourcePatternResolver();
    Resource[] resources = scanner.getResources(matchPattern);

    for (Resource resource : resources) {
        Class<?> clazz = getClassFromResource(resource);
        classes.add(clazz);
    }

    return classes;
}



public static Class getClassFromResource(Resource resource) {
    try {
        String resourceUri = resource.getURI().toString();
        resourceUri = resourceUri.replace(esourceUri.indexOf(".class"), "").replace("/", ".");
        // try printing the resourceUri before calling forName, to see if it is OK.
        return Class.forName(resourceUri);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return null;
}
Bozho
+4  A: 

Here's a basic example, assuming that classes are not JAR-packaged:

// Prepare.
String packageName = "com.example.commands";
List<Class<ICommand>> commands = new ArrayList<Class<ICommand>>();
URL root = Thread.currentThread().getContextClassLoader().getResource(packageName.replace(".", "/"));

// Filter .class files.
File[] files = new File(root.getFile()).listFiles(new FilenameFilter() {
    public boolean accept(File dir, String name) {
        return name.endsWith(".class");
    }
});

// Find classes implementing ICommand.
for (File file : files) {
    String className = file.getName().replaceAll(".class$", "");
    Class<?> cls = Class.forName(packageName + "." + className);
    if (ICommand.class.isAssignableFrom(cls)) {
        commands.add((Class<ICommand>) cls);
    }
}
BalusC
+1  A: 

This would be a very useful tool we need, and JDK should provide some support.

But it's probably better done during build. You know where all your class files are and you can inspect them statically and build a graph. At runtime you can query this graph to get all subtypes. This requires more work, but I believe it really belongs to the build process.

irreputable
Something like the JSR-199 API? See http://stackoverflow.com/questions/1810614/getting-all-classes-from-a-package/1811120#1811120
Pascal Thivent
+4  A: 

Below, an implementation using the JSR-199 API i.e. classes from javax.tools.*:

List<Class> commands = new ArrayList<Class>();

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(
        null, null, null);

Location location = StandardLocation.CLASS_PATH;
String packageName = "commands";
Set<JavaFileObject.Kind> kinds = new HashSet<JavaFileObject.Kind>();
kinds.add(JavaFileObject.Kind.CLASS);
boolean recurse = false;

Iterable<JavaFileObject> list = fileManager.list(location, packageName,
        kinds, recurse);

for (JavaFileObject javaFileObject : list) {
    commands.add(javaFileObject.getClass());
}
Pascal Thivent
Interesting, but `ToolProvider.getSystemJavaCompiler()` returns `null` in both Eclipse and CLI? Is something more needed?
BalusC
After digging, this apparently requires a JDK instead of JRE (which I however have in CLI, I'll dig later why this doesn't work). That would mean that you need to install a JDK in the final/prod environment to get it to work. That may be a showstopper.
BalusC
Indeed, you need a JDK to get a non `null` compiler object (see http://bit.ly/89HtA0) so this API doesn't really target the desktop. It should be OK on the server-side though (most app servers use a JDK after all, e.g. for JSP compilation). But of course, there might be exceptions. Actually, I just wanted to show that there was some support in the JDK even if this isn't a perfect use case for the Compiler API (it's a poor usage here). This API can do more, much more, for example compiling on the fly Java source code generated dynamically in-memory (which is already more interesting).
Pascal Thivent
It's indeed an interesting API. But unfortunately really only for the developer.
BalusC
A: 

Using Johannes Link's ClasspathSuite, I was able to do it like this:

import org.junit.extensions.cpsuite.ClassTester;
import org.junit.extensions.cpsuite.ClasspathClassesFinder;

public static List<Class<?>> getClasses(final Package pkg, final boolean includeChildPackages) {
    return new ClasspathClassesFinder(new ClassTester() {
        @Override public boolean searchInJars() { return true; }
        @Override public boolean acceptInnerClass() { return false; }
        @Override public boolean acceptClassName(String name) {
            return name.startsWith(pkg.getName()) && (includeChildPackages || name.indexOf(".", pkg.getName().length()) != -1);
        }
        @Override public boolean acceptClass(Class<?> c) { return true; }
    }, System.getProperty("java.class.path")).find();
}

The ClasspathClassesFinder looks for class files and jars in the system classpath.

In your specific case, you could modify acceptClass like this:

@Override public boolean acceptClass(Class<?> c) {
    return ICommand.class.isAssignableFrom(c);
}

One thing to note: be careful what you return in acceptClassName, as the next thing ClasspathClassesFinder does is to load the class and call acceptClass. If acceptClassName always return true, you'll end up loading every class in the classpath and that may cause an OutOfMemoryError.

Nicolas Marchildon