java得到一个包的所有类

 public static Class[] getClasses(String pckgname)
   throws ClassNotFoundException {
  ArrayList classes = new ArrayList();
  // Get a File object for the package
  File directory = null;
  try {
   ClassLoader cld = Thread.currentThread().getContextClassLoader();
   if (cld == null)
    throw new ClassNotFoundException("Can't get class loader.");
   String path = '/' + pckgname.replace('.', '/');
   URL resource = cld.getResource(path);
   if (resource == null)
    throw new ClassNotFoundException("No resource for " + path);
   directory = new File(resource.getFile());
  } catch (NullPointerException x) {
   throw new ClassNotFoundException(pckgname + " (" + directory
     + ") does not appear to be a valid package a");
  }
  if (directory.exists()) {
   // Get the list of the files contained in the package
   String[] files = directory.list();
   for (int i = 0; i < files.length; i++) {
    // we are only interested in .class files
    if (files[i].endsWith(".class")) {
     // removes the .class extension
     classes.add(Class.forName(pckgname + '.'
       + files[i].substring(0, files[i].length() - 6)));
  }
   }
  } else
   throw new ClassNotFoundException(pckgname
     + " does not appear to be a valid package b");
  Class[] classesA = new Class[classes.size()];
  classes.toArray(classesA);
  return classesA;
 }

 

这个方法是从sun论坛上找到的,他在eclipse的tomcat6.0环境下测试缺是失败的,跟踪后发现,是在directory.exists()这个判断上失败的,是否是路径等存在什么问题?但是在非调试环境下是通过的。

你可能感兴趣的:(java得到一个包的所有类)