/** * * @param declareClass:类声明,eg:com.HelloWordImpl * @param jarPath:jar包路径,目前只支持file协议,其他需要自己改造 * @param <T>:实例对象,eg:HelloWord的实现类HelloWordImpl * @return */ public static <T> T loadJarAndNewIns(String declareClass, String jarPath) { logger.info("==============================>loadJarAndNewIns declareClass[" + declareClass + "],jarPath[" + jarPath + "]"); ClassLoader cl = null; try { // 从Jar文件得到一个Class加载器 cl = new URLClassLoader(new URL[] { new URL(jarPath) }, Thread.currentThread().getContextClassLoader()); // 从加载器中加载Class Class<?> c = cl.loadClass(declareClass); // 从Class中实例出一个对象 return (T) c.newInstance(); } catch (Exception e) { logger.error("===============================>loadJarAndNewIns fail"); logger.error(e.getMessage()); } return null; }
java加载第三方jar并实例化类
最新推荐文章于 2021-11-02 16:47:07 发布