Is it possible to have the System ClassLoader load .class files specified at run time?

后端 未结 6 1007
[愿得一人]
[愿得一人] 2021-01-01 00:09

I am writing a static analysis tool for an assignment, it analyses Java bytecode using the ASM library. One of the parts of ASM that we use requires (or at least, appears to

6条回答
  •  遥遥无期
    2021-01-01 01:07

    Yes, you can use URLClassLoader

    I have a test where I do load the class at runtime. This class is not in the classpath (nor even exist when the test is run for that matter ), later is it loaded and works great.

    Here's the code.

    void testHello() throws MalformedURLException, ClassNotFoundException {
        URL[] url = {
                new URL("file:/home/oreyes/testwork/")
        };
    
        try {
            new URLClassLoader(url).loadClass("Hello");
            throw new AssertionError("Should've thrown ClassNotFoundException");
        } catch ( ClassNotFoundException cnfe ){}
    
    
        c.process();// create the .class file 
    
        new URLClassLoader(url).loadClass("Hello");
    
        // it works!!
    }
    

    Taken from this question.

提交回复
热议问题