Created
May 31, 2011 08:00
-
-
Save Monomachus/1000129 to your computer and use it in GitHub Desktop.
Package Scanner for Active Objects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.pocketgator.placeholder.common; | |
import java.io.File; | |
import java.net.URL; | |
import java.util.ArrayList; | |
import java.util.List; | |
import net.java.ao.RawEntity; | |
public class PackageScanner { | |
public static Class<? extends RawEntity<?>>[] getClassesInPackage( | |
String pckgname) { | |
File directory = getPackageDirectory(pckgname); | |
if (!directory.exists()) { | |
throw new IllegalArgumentException( | |
"Could not get directory resource for package " + pckgname | |
+ "."); | |
} | |
return getClassesInPackage(pckgname, directory); | |
} | |
private static Class<? extends RawEntity<?>>[] getClassesInPackage( | |
String pckgname, | |
File directory) { | |
List<Class<?>> classes = new ArrayList<Class<?>>(); | |
for (String filename : directory.list()) { | |
if (filename.endsWith(".class")) { | |
String classname = buildClassname(pckgname, filename); | |
try { | |
Class<?> classToAdd = Class.forName(classname); | |
if (classToAdd.isInterface() | |
&& classToAdd != RawEntity.class | |
&& RawEntity.class.isAssignableFrom(classToAdd)) { | |
classes.add(Class.forName(classname)); | |
} | |
} catch (ClassNotFoundException e) { | |
System.err.println("Error creating class " + classname); | |
} | |
} | |
} | |
return classes.toArray(new Class[classes.size()]); | |
} | |
private static String buildClassname(String pckgname, String filename) { | |
return pckgname + '.' + filename.replace(".class", ""); | |
} | |
private static File getPackageDirectory(String pckgname) { | |
ClassLoader cld = Thread.currentThread().getContextClassLoader(); | |
if (cld == null) { | |
throw new IllegalStateException("Can't get class loader."); | |
} | |
URL resource = cld.getResource(pckgname.replace('.', '/')); | |
if (resource == null) { | |
throw new RuntimeException("Package " + pckgname | |
+ " not found on classpath."); | |
} | |
return new File(resource.getFile()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment