使用URLClassLoader动态加载Jar/class(加载了jar就相当于加载了jar里面的class)

public static void loadJar(String path){
    // 系统类库路径  
    File libPath = new File(path);  
    // 获取所有的.jar和.zip文件  
    File[] jarFiles = libPath.listFiles(new FilenameFilter() {  
        public boolean accept(File dir, String name) {  
            return name.endsWith(".jar") || name.endsWith(".zip");  
    if (jarFiles != null) {  
        // 从URLClassLoader类中获取类所在文件夹的方法  
        // 对于jar文件,可以理解为一个存放class文件的文件夹  
        Method method = null;
        try {
            method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
        } catch (NoSuchMethodException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (SecurityException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        boolean accessible = method.isAccessible();     // 获取方法的访问权限  
        try {  
            if (accessible == false) {  
                method.setAccessible(true);     // 设置方法的访问权限  
            // 获取系统类加载器  
            URLClassLoader classLoader = (URLClassLoader) Thread.currentThread().getContextClassLoader();;  
            for (File file : jarFiles) {
                try {  
                    URL url = file.toURI().toURL(); 
                    method.invoke(classLoader, url);    
                    System.out.println("读取jar文件成功"+file.getName());
                } catch (Exception e) {  
                    System.out.println("读取jar文件失败");
        } finally {  
            method.setAccessible(accessible);  
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.File;
import java.io.FilenameFilter;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;
import java.util.stream.Collectors;
@SpringBootTest(classes = Application.class)
//@RunWith(SpringRunner.class)
public class Test1 {
    @Test
    public void testUrlClassLoader() {
        String path = "/Users/**/Downloads/home/admin/**/**/**/2.1.1-cdh6.1.1";
        loadJar(path);
        //测试是否能够加载jar里面的类,测试成功加载了jar里面相关的类
        Class.forName("org.apache.hadoop.hive.metastore.api.AbortTxnRequest");
        Class.forName("org.apache.hadoop.hive.common.metrics.LegacyMetrics");
        Class.forName("org.apache.hadoop.hive.metastore.HiveMetaStoreClient");
    public static void loadJar(String path){
        // 系统类库路径
        File libPath = new File(path);
        // 获取所有的.jar和.zip文件
        File[] jarFiles = libPath.listFiles(new FilenameFilter() {
            public boolean accept(File dir, String name) {
                return name.endsWith(".jar") || name.endsWith(".zip");
        if (jarFiles != null) {
            // 从URLClassLoader类中获取类所在文件夹的方法
            // 对于jar文件,可以理解为一个存放class文件的文件夹
            Method method = null;
            try {
                method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
            } catch (NoSuchMethodException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (SecurityException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            boolean accessible = method.isAccessible();     // 获取方法的访问权限
            try {
                if (accessible == false) {
                    method.setAccessible(true);     // 设置方法的访问权限
                // 获取系统类加载器
                URLClassLoader classLoader = (URLClassLoader) Thread.currentThread().getContextClassLoader();
                for (File file : jarFiles) {
                    try {
                        URL url = file.toURI().toURL();
                        method.invoke(classLoader, url);
                        System.out.println("读取jar文件成功"+file.getName());
                    } catch (Exception e) {
                        System.out.println("读取jar文件失败");
            } finally {
                method.setAccessible(accessible);
@Test
public void testUrlClassLoader() throws Exception {
    String path1 = "/Users/***/Downloads/home/admin/***/***/hive/2.1.1-cdh6.1.1";
    String path2 = "/Users/***/Downloads/home/admin/***/***/hive/2.3.0";
    URLClassLoader classLoader = loadJarOne(path2);
    Thread.currentThread().setContextClassLoader(classLoader);
    Class<?> clazz = classLoader.loadClass("org.apache.hadoop.hive.metastore.HiveMetaStoreClient");
    clazz.getDeclaredConstructor(org.apache.hadoop.conf.Configuration.class).newInstance(new HiveConf());
private static URLClassLoader loadJarOne(String path) {
    // 系统类库路径
    File libPath = new File(path);
    // 获取所有的.jar和.zip文件
    File[] jarFiles = libPath.listFiles(new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return name.endsWith(".jar") || name.endsWith(".zip");
    int i = 0;
    URL[] urls = new URL[jarFiles.length];
    if (jarFiles != null) {
        for (File file : jarFiles) {
            try {
                urls[i++] = file.toURI().toURL();
                System.out.println("读取jar文件成功" + file.getName());
            } catch (Exception e) {
                System.out.println("读取jar文件失败");
    System.out.println(JSON.toJSONString(urls));
    URLClassLoader urlClassLoader = new URLClassLoader(urls);
    return urlClassLoader;
类加载器有多种,这里不一一科普,我们在程序中的 Thread.currentThread().getContextClassLoader() 指的是App应用类加载器。

比较好的文章: blog.csdn.net/chengqiumin…

  • 私信
    1,302