Dynamically loading Jar and instanciate an Object of a loaded Class

前端 未结 1 1832
逝去的感伤
逝去的感伤 2021-01-07 03:32

I try to load dynamically a jar into my Java project.

Here\'s the class loader\'s code :

public class ClassLoad {

public static void main(String[] a         


        
相关标签:
1条回答
  • 2021-01-07 04:03

    It looks like your file URL is invalid.

    "File URIs in Windows" says

    For the local Windows file path

    C:\Documents and Settings\davris\FileSchemeURIs.doc

    The corresponding valid file URI in Windows is:

    file:///C:/Documents%20and%20Settings/davris/FileSchemeURIs.doc

    which shows that three slashes are needed after the colon, but the URL you are computing in

    String filePath = new String("C:/Users/Mehdi/Desktop/JavaClassLoader/jarred.jar");
    
    URL myJarFile = null;
    try {
        myJarFile = new URL("file://"+filePath);
    

    has only two slashes after the file:. Perhaps

        myJarFile = new URL("file://"+filePath);
    

    should be

        myJarFile = new URL("file:///"+filePath);
    

    or alternatively you could use java.io.File.toURI thus

    File myJarFile = new File("C:\\Users\\Mehdi\\Desktop\\JavaClassLoader\\jarred.jar");
    if (!myJarFile.isFile()) {
      throw new FileNotFoundException("Missing required JAR: " + myJarFile.toString());
    }
    URL myJarUrl = myJarFile.toURI().toURL();
    

    with appropriate exception handling.

    0 讨论(0)
提交回复
热议问题