/** * Get classloader singleton instance. * * @param files Files. * @param parent Parent classloader. * @return Instance of Jar class loader. * @throws IOException If fies can't be read, */ public static synchronized GridJarClassLoader getInstance(List<String> files, ClassLoader parent) throws IOException{ if (instance == null) instance = new GridJarClassLoader(files, parent); return instance; }
/** * Constructor. * * @param files Files. * @param parent Parent classloader. * @throws IOException If fies can't be read, */ private GridJarClassLoader(Iterable<String> files, ClassLoader parent) throws IOException { super(parent); clsArrs = new HashMap<>(); for (String fileName: files) readJarFile(fileName); }
/** {@inheritDoc} */ @Override protected synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { boolean excluded = false; for (String cls: excludedCls) if (name.startsWith(cls)) { excluded = true; break; } // If class is from Jar file(s) and not in excluded (note we use name with '.'). if (clsArrs.containsKey(name) && !excluded) { Class<?> cls = findLoadedClass(name); if (cls == null) cls = findClass(name); if (resolve) resolveClass(cls); return cls; } return super.loadClass(name, resolve); }
/** {@inheritDoc} */ @Override protected Class<?> findClass(String name) throws ClassNotFoundException { SecurityManager sm = System.getSecurityManager(); if (sm != null) { int i = name.lastIndexOf('.'); if (i >= 0) sm.checkPackageDefinition(name.substring(0, i)); } byte[] buf = clsArrs.get(name); if (buf != null) return defineClass(name, buf, 0, buf.length, (CodeSource)null); throw new ClassNotFoundException(name); }
/** * Reads JAR file and stored classes locally. * * @param fileName Name of file to read. * @throws IOException If read failed. */ private void readJarFile(String fileName) throws IOException { JarEntry je; JarInputStream jis = new JarInputStream(new FileInputStream(fileName)); while ((je = jis.getNextJarEntry()) != null) { String jarName = je.getName(); if (jarName.endsWith(".class")) loadClassBytes(jis, jarName); // Else ignore it; it could be an image or audio file. jis.closeEntry(); } }