Skip to content

URLClassLoader

Ricky Fung edited this page Aug 21, 2017 · 7 revisions

简介

URLClassLoader 是 ClassLoader的子类,它用于从指定URL加载类和资源。

官方Doc说明如下:

This class loader is used to load classes and resources from a search path of URLs referring to both JAR files and directories. Any URL that ends with a '/' is assumed to refer to a directory. Otherwise, the URL is assumed to refer to a JAR file which will be opened as needed.

The AccessControlContext of the thread that created the instance of URLClassLoader will be used when subsequently loading classes and resources.

The classes that are loaded are by default granted permission only to access the URLs specified when the URLClassLoader was created.

下面来看一个例子,在该例子中,我们利用URLClassLoader加载jar并运行其中的类的某个方法。

示例

HelloService.java

package com.mindflow.demo;

public interface HelloService {

    String hello(String msg);
}

HelloService 接口实现类:

package com.mindflow.demo;

public class HelloServiceImpl implements HelloService {

    @Override
    public String hello(String msg) {
        String result = String.format("hello, %s", msg);
        System.out.println(result);
        return result;
    }
}

将上述两个类打包到demo.jar 并复制到/data 目录下,然后我们新建一个项目 使用URLClassLoader来加载demo.jar,如下:

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

/**
 * ${DESCRIPTION}
 *
 * @author Ricky Fung
 */
public class App {

    public static void main(String[] args) throws MalformedURLException, ClassNotFoundException, IllegalAccessException, InstantiationException {
        File file = new File("/data/demo.jar");
        URL url = file.toURI().normalize().toURL();
        //自定义类加载器
        URLClassLoader loader = new URLClassLoader(new URL[] { url }, Thread.currentThread().getContextClassLoader());
        //load class
        Class cls = loader.loadClass("com.mindflow.demo.HelloServiceImpl");
        //构造类实例
        HelloService helloService = (HelloService) cls.newInstance();
        helloService.hello("ricky");
    }
}

JarClassLoader

JarClassLoader

Clone this wiki locally