动态记载外部jar或者class并执行

package com.liufei.demo.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLStreamHandler;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/ping")
public class PingController {

    @GetMapping
    public String ping() {
        return "ok";
    }

    @GetMapping("test")
    public String test(@RequestParam String jarPath, @RequestParam String className) throws Exception {
        File file = new File(jarPath);
        if (!file.exists()) {
            throw new Exception("文件不存在...");
        }
        List<URL> urlList = new ArrayList<>();
        try {
            urlList.add(new File("d:\\opt\\fastjson-1.2.78.jar").toURI().toURL());
            urlList.add(new File("d:\\opt\\commons-lang3-3.9.jar").toURI().toURL());
            urlList.add(file.toURI().toURL());

            URL[] urls = urlList.toArray(new URL[0]);
            URLClassLoader classLoader = new URLClassLoader(urls);

            Class<?> clazz = classLoader.loadClass(className);
            Method test = clazz.getMethod("test", String.class);
            test.invoke(clazz.newInstance(), "zs");

            classLoader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "ok";
    }

    @GetMapping("loadClass")
    public String loadClass(@RequestParam String jarPath, @RequestParam String className) throws Exception {
        File file = new File(jarPath);
        if (!file.exists()) {
            throw new Exception("文件不存在...");
        }
        List<URL> urlList = new ArrayList<>();
        try {
            // 这里的jarPath传的是目录。如:D:\opt\demo-jar-with-dependencies。。。。 className = TestCase
            String repository =(new URL("file", null, file.getCanonicalPath() + File.separator)).toString();
            URLStreamHandler streamHandler = null;
            urlList.add(new URL(null, repository, streamHandler));
            urlList.add(new File("d:\\opt\\fastjson-1.2.78.jar").toURI().toURL());
            urlList.add(new File("d:\\opt\\commons-lang3-3.9.jar").toURI().toURL());

            URL[] urls = urlList.toArray(new URL[0]);
            URLClassLoader classLoader = new URLClassLoader(urls);

            Class<?> clazz = classLoader.loadClass(className);
            Method test = clazz.getMethod("test", String.class);
            test.invoke(clazz.newInstance(), "zs");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "ok";
    }
}

  

posted @ 2022-03-21 23:43  刘翊扬  阅读(52)  评论(0编辑  收藏  举报