I have written an application which manages several plugins which are provided as jars. I load the plugin classes using an URLClassLoader which works as supposed.
But now I am writing a plugin which loads some resources which are stored inside the jar. If I start this plugin as a standalone application everything works, but if I start it from inside my application I get a NullPointerException when I try to open the resources InputStream.
I open the stream like this:
this.getClass().getResourceAsStream("/templates/template.html"); My Eclipse project structure looks like:
src | + My source files resources | + templates | + template.html The following loads my plugins:
private List<Class<?>> loadClasses(final File[] jars) { List<Class<?>> classes = new ArrayList<Class<?>>(); URL[] urls = getJarURLs(jars); URLClassLoader loader = new URLClassLoader(urls); for (File jar : jars) { JarFile jarFile = null; try { jarFile = new JarFile(jar); } catch (IOException e) { // Skip this jar if it can not be opened continue; } Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (isClassFile(entry.getName())) { String className = entry.getName().replace("/", ".").replace(".class", ""); Class<?> cls = null; try { cls = loader.loadClass(className); } catch (ClassNotFoundException e) { // Skip this jar if a class inside it can not be loaded continue; } classes.add(cls); } } try { jarFile.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } try { loader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return classes; } /** * Checks if a path points to a class file or not. * * @param path the filename to check * @return {@code true} if the path points to a class file or {@code false} * if not */ private boolean isClassFile(final String path) { return path.toLowerCase().endsWith(".class") && !path.toLowerCase().contains("package-info"); } Then I make instances from this classes using newInstance().
I think that the root path of the plugins jar is not the same as the root path of the application or that not all contents of the jar files are loaded or both...
Can someone help me?
this.getClass().getResource("/templates/template.html);works for me fine when trying to access something in a jar.