I wrote java program for loading classes at runtime from jar file or class files
Hope this post will help somebody...
Hope this post will help somebody...
package com.dukesoftware.utils.reflect; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.net.URI; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.jar.JarEntry; import java.util.jar.JarFile; public class DynamicClassLoader { public static List<Class<?>> readAllClassesFormJarFile(File jarFilePath) throws IOException{ List<Class<?>> classes = new ArrayList<>(); URL[] urls = { new URL("jar:" + jarFilePath.toURI().toURL() + "!/") }; URLClassLoader loader = URLClassLoader.newInstance(urls); for(Enumeration<JarEntry> en = new JarFile(jarFilePath).entries(); en.hasMoreElements();){ final String name = en.nextElement().getName(); if(name.endsWith(".class")){ try { classes.add(loader.loadClass(toClassName(name))); } catch (ClassNotFoundException e) { throw new IllegalStateException("Should not happen:", e); } } } return classes; } public static List<Class<?>> readAllClasses(File rootClasspathDirectory) throws IOException{ URI rootURI = rootClasspathDirectory.toURI(); List<Class<?>> classes = new ArrayList<>(); URLClassLoader loader = new URLClassLoader(new URL[]{ rootURI.toURL()}); for(File classFile : listFiles(rootClasspathDirectory, acceptExtensionOnly("class"))){ URI uri = rootURI.relativize(classFile.toURI()); final String clazz = uri.toString(); try { classes.add(loader.loadClass(toClassName(clazz))); } catch (ClassNotFoundException e) { throw new IllegalStateException("Should not happen:", e); } } return classes; } private static String toClassName(String uri) { return uri.substring(0, uri.lastIndexOf(".class")).replaceAll("/", "."); } // list files public static List<File> listFiles(File file, FileFilter filter){ ArrayList<File> result = new ArrayList<>(); listFiles(file, filter, result); return result; } public static void listFiles(File file, FileFilter filter, List<File> result){ if(file.isDirectory()){ final File[] files = file.listFiles(); if(files != null){ for(File child: files){ result.add(child); } } } else{ if(filter.accept(file)){ listFiles(file, filter, result); } } } // file filter which only accepts given extension public static FileFilter acceptExtensionOnly(final String ext){ return new FileFilter() { @Override public boolean accept(File pathname) { return pathname.getName().endsWith("." + ext); } }; } }
コメント