一、前言
通过java.net.URLClassLoader定义JarLoader加载器类,对指定Properties配置中追加加载jar包的路径地址,详情参见代码示例。
二、代码示例
1. JarLoader类
import java.net.URL;@b@import java.net.URLClassLoader;@b@import java.util.Properties;@b@@b@public class JarLoader {@b@ @b@ private static String CLASS_PATH = JarLoader.class.getResource("/").getPath();@b@ private static String CLASS_LIB_PATH = CLASS_PATH + "lib/";@b@ private static String DEFAULT_FILE = CLASS_PATH + "jar.config.properties";@b@@b@ public static void load()@b@ throws Exception@b@ {@b@ Properties prop = PropertiesReader.read(DEFAULT_FILE);@b@ String jarName = prop.getProperty("account.jar");@b@ loadJar(CLASS_LIB_PATH + jarName);F@b@ }@b@@b@ public static void loadJar(String jarFileName) throws Exception {@b@ URL url = new URL(jarFileName);@b@ URLClassLoader myClassLoader = new URLClassLoader(new URL[] { url },@b@ Thread.currentThread().getContextClassLoader());@b@@b@ Class myClass = myClassLoader@b@ .loadClass("com.xwood.poratal.account.entity.Account");@b@ Object action = myClass.newInstance();@b@ }@b@}
2. PropertiesReader类
import java.io.BufferedInputStream;@b@import java.io.File;@b@import java.io.FileInputStream;@b@import java.io.IOException;@b@import java.io.InputStream;@b@import java.util.Properties;@b@@b@public class PropertiesReader {@b@@b@ private static String prop_suffix = ".properties";@b@@b@ public static Properties readPath(String filePath) throws Exception {@b@ Properties prop = new Properties();@b@@b@ File root = new File(filePath);@b@ readFile(prop, root);@b@@b@ return prop;@b@ }@b@@b@ public static void readFile(Properties prop, File file) throws IOException {@b@ File[] arr$;@b@ int i$;@b@ if (file.isDirectory()) {@b@ File[] files = file.listFiles();@b@ arr$ = files;@b@ int len$ = arr$.length;@b@ for (i$ = 0; i$ < len$; ++i$) {@b@ File f = arr$[i$];@b@ readFile(prop, f);@b@ }@b@ } else if ((file.isFile()) && (file.getName().endsWith(prop_suffix))) {@b@ InputStream in = null;@b@ try {@b@ in = new BufferedInputStream(new FileInputStream(file));@b@ prop.load(in);@b@ } finally {@b@ if (in != null)@b@ in.close();@b@ }@b@ }@b@ }@b@@b@ public static Properties read(String fileName) throws Exception {@b@ Properties prop = null;@b@ InputStream in = null;@b@ try {@b@ in = new BufferedInputStream(new FileInputStream(fileName));@b@@b@ prop = new Properties();@b@ prop.load(in);@b@ } finally {@b@ if (in != null)@b@ in.close();@b@ }@b@@b@ return prop;@b@ }@b@@b@ public static Properties read(InputStream is) throws Exception {@b@ Properties prop = null;@b@@b@ prop = new Properties();@b@ prop.load(is);@b@@b@ return prop;@b@ }@b@}