目的:
    动态加载jar包,实现插件的机制。

    示例:

    1. package com.alvin;
    2. import org.springframework.boot.SpringApplication;
    3. import org.springframework.boot.autoconfigure.SpringBootApplication;
    4. import org.springframework.web.bind.annotation.GetMapping;
    5. import org.springframework.web.bind.annotation.RestController;
    6. import java.net.URL;
    7. import java.net.URLClassLoader;
    8. @SpringBootApplication
    9. @RestController
    10. public class MainApplication {
    11. public static void main(String[] args) {
    12. SpringApplication.run(MainApplication.class, args);
    13. }
    14. @GetMapping("/")
    15. public Boolean test(String query) throws Exception {
    16. String jarPath = "D:\\code\\java-plugin\\plugin1\\target\\plugin1-1.0-SNAPSHOT.jar";
    17. String className = "com.alvin.service.impl.Plugin1";
    18. String methodName = "isTrue";
    19. return (Boolean) exec(jarPath, className, methodName, query);
    20. }
    21. public static Object exec(String jarPath, String className, String methodName, String query) throws Exception {
    22. URLClassLoader classLoader = new URLClassLoader(new URL[]{new URL("file:" + jarPath)}, Thread.currentThread().getContextClassLoader());
    23. Class demo = classLoader.loadClass(className);
    24. Object object = demo.newInstance();
    25. Object invoke = demo.getMethod(methodName, String.class).invoke(object, new Object[]{query});
    26. return invoke;
    27. }
    28. }