Advertisement
Guest User

Untitled

a guest
Sep 7th, 2018
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.30 KB | None | 0 0
  1. package engine.util;
  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.net.URL;
  5. import java.util.Enumeration;
  6. import java.util.LinkedList;
  7. import java.util.List;
  8.  
  9. public final class ClassFinder {
  10.  
  11.     private final static char DOT = '.';
  12.     private final static char SLASH = '/';
  13.     private final static String CLASS_SUFFIX = ".class";
  14.     private final static String BAD_PACKAGE_ERROR = "Unable to get resources from path '%s'. Are you sure the given '%s' package exists?";
  15.  
  16.     public final static Class<?>[] find(final String scannedPackage) {
  17.         final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
  18.         final String scannedPath = scannedPackage.replace(DOT, SLASH);
  19.         final Enumeration<URL> resources;
  20.         try {
  21.             resources = classLoader.getResources(scannedPath);
  22.         } catch (IOException e) {
  23.             throw new IllegalArgumentException(String.format(BAD_PACKAGE_ERROR, scannedPath, scannedPackage), e);
  24.         }
  25.         final List<Class<?>> classes = new LinkedList<Class<?>>();
  26.         while (resources.hasMoreElements()) {
  27.             final File file = new File(resources.nextElement().getFile());
  28.             classes.addAll(find(file, scannedPackage));
  29.         }
  30.         return classes.toArray(new Class[classes.size()]);
  31.     }
  32.  
  33.     private final static List<Class<?>> find(final File file, final String scannedPackage) {
  34.         final List<Class<?>> classes = new LinkedList<Class<?>>();
  35.         if (file.isDirectory()) {
  36.             for (File nestedFile : file.listFiles()) {
  37.                 classes.addAll(find(nestedFile, scannedPackage));
  38.             }
  39.         //File names with the $1, $2 holds the anonymous inner classes, we are not interested on them.
  40.         } else if (file.getName().endsWith(CLASS_SUFFIX) && !file.getName().contains("$")) {
  41.  
  42.             final int beginIndex = 0;
  43.             final int endIndex = file.getName().length() - CLASS_SUFFIX.length();
  44.             final String className = file.getName().substring(beginIndex, endIndex);
  45.             try {
  46.                 final String resource = scannedPackage + DOT + className;
  47.                 classes.add(Class.forName(resource));
  48.             } catch (ClassNotFoundException ignore) {
  49.             }
  50.         }
  51.         return classes;
  52.     }
  53.  
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement