How to use URLClassLoader to load a *.class file?

后端 未结 5 2134
旧时难觅i
旧时难觅i 2020-11-27 16:13

I\'m playing around with Reflection and I thought I\'d make something which loads a class and prints the names of all fields in the class. I\'ve made a small hello world typ

相关标签:
5条回答
  • 2020-11-27 16:31

    I was having a similar problem but my class file was residing inside a package named "customElements". In such scenarios the URL needs to be constructed till the folder just above the root package and in the load method the complete name of the class including the package should be passed. For example, in my case; URL was like:

    File customElementsDir = new File("D:/My Space");
    //File customElementsDir = new File("D:\\customElements");
    URL[] urls = null;
    try {
        URL url = customElementsDir.toURI().toURL();
        urls = new URL[] { url };
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    

    And actual loading was like:

    clazz = childFirstClassLoader
                .loadClass("customElements.CustomLoadableClass");
    

    Where childFirstClassLoader is my classloader.

    0 讨论(0)
  • 2020-11-27 16:33

    From the Javadocs for the URLClassLoader(URL[]) constructor:

    Constructs a new URLClassLoader for the specified URLs using the default delegation parent ClassLoader. The URLs will be searched in the order specified for classes and resources after first searching in the parent class loader. Any URL that ends with a '/' is assumed to refer to a directory. Otherwise, the URL is assumed to refer to a JAR file which will be downloaded and opened as needed.

    So you have two options:

    1. Refer to the directory that the .class file is in
    2. Put the .class file into a JAR and refer to that

    (1) is easier in this case, but (2) can be handy if you're using networked resources.

    0 讨论(0)
  • 2020-11-27 16:37

    I had the same problem but I found this as a solution:

    System.getProperty("java.class.path")
    

    This give you the jar, and classes path. From here you are able to manage your process.

    0 讨论(0)
  • 2020-11-27 16:49

    You have to load the class by giving the fully qualified class name that is class name with with its package path as,

    Class c = ucl.loadClass("com.mypackage.IndependentClass");
    
    0 讨论(0)
  • 2020-11-27 16:56

    You must provide the directories or the jar files containing your .class files to the URLClassLoader:

    classUrl = new URL("file:///home/kent/eclipsews/SmallExample/bin/");
    

    And yes, you can load as many classes as you like

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