java程序执行过程中动态加载Jar包

 

最近的系统需要添加一个新的功能,就是在不重启服务的情况下,动态加载用户上传的jar包,先来过一遍简单的jar包的动态加载。

  • 方法一:通过配置文件读取jar包位置

  • 方法二:把jar的位置放置于固定的位置

 

首先来看一下大致文件结构:

 

第一步,定义一个接口:

public interface InterfaceAction {

    String action();

}

 

第二步,写测试这个接口的实现类

public class TestAction implements InterfaceAction {

    public String action() {

        System.out.println("TestAction");

        retrun "action()";

    }

}

第三步,把TestCL2编译打包成jar包,然后丢到F:/jar/下

 

第四步,写测试类来测试结果

public class TestMain {

    public static void main(String[] args) {

        try {

            //第一种  配置成文件格式

            File file = new File("F:\\jar\\test.txt");

            BufferedReader in = new BufferedReader(new FileReader(file));

            String s = new String();

            while ((s = in.readLine()) != null) {

                System.out.println(s);

                URL url = new URL(s);

                URLClassLoader myClassLoader = new URLClassLoader(new URL[] { url }, Thread.currentThread().getContextClassLoader());

                Class<? extends InterfaceAction> myClass = (Class<? extends InterfaceAction>) myClassLoader.loadClass("com.java.jarloader.TestAction");

                InterfaceAction action = (InterfaceAction) myClass.newInstance();

                String str = action.action();

                System.out.println(str);



                //第二种 

                URL url1 = new URL("file:F:\\jar\\TestCL2.jar");

                URLClassLoader myClassLoader1 = new URLClassLoader(new URL[] { url1 }, Thread.currentThread().getContextClassLoader());

                Class<?> myClass1 = myClassLoader1.loadClass("com.java.jarloader.TestAction");

                InterfaceAction action1 = (InterfaceAction) myClass1.newInstance();

                String str1 = action1.action();

                System.out.println(str1);

            }

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

}

 

第五步,结果验证。

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sileiH

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值