如何在java中的类路径中找到资源? 特别是以.hbm.xml结尾的东西

如何在java中的类路径中找到资源? 特别是以.hbm.xml结尾的东西。

我的目标是获取以“.hbm.xml”结尾的类路径上的所有资源的列表。

你必须得到一个类加载器 ,并测试它是否是URLClassLoader。 如果是这样,请转发并获取其url 。 从那里,打开每个作为JarFile并查看其条目 。 对每个条目应用正则表达式 ,看看它是否是您感兴趣的条目。

显然,这并不快。 最好给出一个在类路径中查找的名称,可能在每个classpath元素的META-INF目录中的标准文件名中列出,类似于ServiceProvider工具使用的技术。 请注意,您可以在类路径中列出具有给定名称的所有文件 。

我们的ClassLoaderUtil方法findClasses可能是适应您需求的良好起点。

 public class ClassLoaderUtil { /** * Recursive method used to find all classes in a given path (directory or zip file url). Directories * are searched recursively. (zip files are * Adapted from http://snippets.dzone.com/posts/show/4831 and extended to support use of JAR files * * @param path The base directory or url from which to search. * @param packageName The package name for classes found inside the base directory * @param regex an optional class name pattern. eg .*Test * @return The classes */ private static TreeSet findClasses(String path, String packageName, Pattern regex) throws Exception { TreeSet classes = new TreeSet(); if (path.startsWith("file:") && path.contains("!")) { String[] split = path.split("!"); URL jar = new URL(split[0]); ZipInputStream zip = new ZipInputStream(jar.openStream()); ZipEntry entry; while ((entry = zip.getNextEntry()) != null) { if (entry.getName().endsWith(".class")) { String className = entry.getName().replaceAll("[$].*", "").replaceAll("[.]class", "").replace('/', '.'); if (className.startsWith(packageName) && (regex == null || regex.matcher(className).matches())) classes.add(className); } } } File dir = new File(path); if (!dir.exists()) { return classes; } File[] files = dir.listFiles(); for (File file : files) { if (file.isDirectory()) { assert !file.getName().contains("."); classes.addAll(findClasses(file.getAbsolutePath(), packageName + "." + file.getName(), regex)); } else if (file.getName().endsWith(".class")) { String className = packageName + '.' + file.getName().substring(0, file.getName().length() - 6); if (regex == null || regex.matcher(className).matches()) classes.add(className); } } return classes; } public static  List instances(Class[] classList) { List tList = new LinkedList(); for(Class tClass : classList) { try { // Only try to instantiate real classes. if(! Modifier.isAbstract(tClass.getModifiers()) && ! Modifier.isInterface(tClass.getModifiers())) { tList.add(tClass.newInstance()); } } catch (Throwable t) { throw new RuntimeException(t.getMessage(), t); } } return tList; } public static Class[] findByPackage(String packageName, Class isAssignableFrom) { Class[] clazzes = getClassesInPackage(packageName, null); if(isAssignableFrom == null) { return clazzes; } else { List filteredList = new ArrayList(); for(Class clazz : clazzes) { if(isAssignableFrom.isAssignableFrom(clazz)) filteredList.add(clazz); } return filteredList.toArray(new Class[0]); } } /** * Scans all classes accessible from the context class loader which belong to the given package and subpackages. * Adapted from http://snippets.dzone.com/posts/show/4831 and extended to support use of JAR files * * @param packageName The base package * @param regexFilter an optional class name pattern. * @return The classes */ public static Class[] getClassesInPackage(String packageName, String regexFilter) { Pattern regex = null; if (regexFilter != null) regex = Pattern.compile(regexFilter); try { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); assert classLoader != null; String path = packageName.replace('.', '/'); Enumeration resources = classLoader.getResources(path); List dirs = new ArrayList(); while (resources.hasMoreElements()) { URL resource = resources.nextElement(); dirs.add(resource.getFile()); } TreeSet classes = new TreeSet(); for (String directory : dirs) { classes.addAll(findClasses(directory, packageName, regex)); } ArrayList classList = new ArrayList(); for (String clazz : classes) { classList.add(Class.forName(clazz)); } return classList.toArray(new Class[classes.size()]); } catch (Exception e) { e.printStackTrace(); return null; } } } 

MyClass.class.getClassLoader()。getResourceAsStream(“Person.hbm.xml”)是查找它的一种方法。