How to load JAR files dynamically at Runtime?

前端 未结 20 3190
伪装坚强ぢ
伪装坚强ぢ 2020-11-21 05:15

Why is it so hard to do this in Java? If you want to have any kind of module system you need to be able to load JAR files dynamically. I\'m told there\'s a way of doing it b

相关标签:
20条回答
  • 2020-11-21 05:54

    For dynamic uploading of jar files, you can use my modification of URLClassLoader. This modification has no problem with changing the jar file during application operation, like the standard URLClassloader. All loaded jar files are loaded into RAM and thus independent of the original file.

    In-memory jar and JDBC class loader

    0 讨论(0)
  • 2020-11-21 05:55

    While most solutions listed here are either hacks (pre JDK 9) hard to configure (agents) or just don't work anymore (post JDK 9) I find it really surprising that nobody mentioned a clearly documented method.

    You can create a custom system class loader and then you're free to do whatever you wish. No reflection required and all classes share the same classloader.

    When starting the JVM add this flag:

    java -Djava.system.class.loader=com.example.MyCustomClassLoader
    

    The classloader must have a constructor accepting a classloader, which must be set as its parent. The constructor will be called on JVM startup and the real system classloader will be passed, the main class will be loaded by the custom loader.

    To add jars just call ClassLoader.getSystemClassLoader() and cast it to your class.

    Check out this implementation for a carefully crafted classloader. Please note, you can change the add() method to public.

    0 讨论(0)
  • 2020-11-21 05:55

    In case anyone searches for this in the future, this way works for me with OpenJDK 13.0.2.

    I have many classes that I need to instantiate dynamically at runtime, each potentially with a different classpath.

    In this code, I already have an object called pack, that holds some metadata about the class I am trying to load. The getObjectFile() method returns the location of the class file for the class. The getObjectRootPath() method returns the path to the bin/ directory containing the class files that include the class I am trying to instantiate. The getLibPath() method returns the path to a directory containing the jar files constituting the classpath for the module the class is a part of.

    File object = new File(pack.getObjectFile()).getAbsoluteFile();
    Object packObject;
    try {
        URLClassLoader classloader;
    
        List<URL> classpath = new ArrayList<>();
        classpath.add(new File(pack.getObjectRootPath()).toURI().toURL());
        for (File jar : FileUtils.listFiles(new File(pack.getLibPath()), new String[] {"jar"}, true)) {
            classpath.add(jar.toURI().toURL());
        }
        classloader = new URLClassLoader(classpath.toArray(new URL[] {}));
    
        Class<?> clazz = classloader.loadClass(object.getName());
        packObject = clazz.getDeclaredConstructor().newInstance();
    
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }
    return packObject;
    

    I was using the Maven dependency: org.xeustechnologies:jcl-core:2.8 to do this before, but after moving past JDK 1.8, it sometimes froze and never returned being stuck "waiting for references" at Reference::waitForReferencePendingList().

    I am also keeping a map of class loaders so that they can be reused if the class I am trying to instantiate is in the same module as a class that I have already instantiated, which I would recommend.

    0 讨论(0)
  • 2020-11-21 05:56

    please take a look at this project that i started: proxy-object lib

    This lib will load jar from file system or any other location. It will dedicate a class loader for the jar to make sure there are no library conflicts. Users will be able to create any object from the loaded jar and call any method on it. This lib was designed to load jars compiled in Java 8 from the code base that supports Java 7.

    To create an object:

        File libDir = new File("path/to/jar");
    
        ProxyCallerInterface caller = ObjectBuilder.builder()
                .setClassName("net.proxy.lib.test.LibClass")
                .setArtifact(DirArtifact.builder()
                        .withClazz(ObjectBuilderTest.class)
                        .withVersionInfo(newVersionInfo(libDir))
                        .build())
                .build();
        String version = caller.call("getLibVersion").asString();
    

    ObjectBuilder supports factory methods, calling static functions, and call back interface implementations. i will be posting more examples on the readme page.

    0 讨论(0)
  • 2020-11-21 05:56

    I personally find that java.util.ServiceLoader does the job pretty well. You can get an example here.

    0 讨论(0)
  • 2020-11-21 05:58

    How about the JCL class loader framework? I have to admit, I haven't used it, but it looks promising.

    Usage example:

    JarClassLoader jcl = new JarClassLoader();
    jcl.add("myjar.jar"); // Load jar file  
    jcl.add(new URL("http://myserver.com/myjar.jar")); // Load jar from a URL
    jcl.add(new FileInputStream("myotherjar.jar")); // Load jar file from stream
    jcl.add("myclassfolder/"); // Load class folder  
    jcl.add("myjarlib/"); // Recursively load all jar files in the folder/sub-folder(s)
    
    JclObjectFactory factory = JclObjectFactory.getInstance();
    // Create object of loaded class  
    Object obj = factory.create(jcl, "mypackage.MyClass");
    
    0 讨论(0)
提交回复
热议问题