Can a directory be added to the class path at runtime?

前端 未结 3 1821
执念已碎
执念已碎 2020-12-01 03:50

In order to better understand how things works in Java, I\'d like to know if I can dynamically add, at runtime, a directory to the class path.

For example, if I laun

3条回答
  •  粉色の甜心
    2020-12-01 03:57

    Yes, you can use URLClassLoader.. see example here. Doesn't use reflection.

    -- edit --

    Copying example from the link as suggested.

    import javax.naming.*;
    import java.util.Hashtable;
    import java.net.URLClassLoader;
    import java.net.URL;
    import java.net.MalformedURLException;
    
    public class ChangeLoader {
    
        public static void main(String[] args) throws MalformedURLException {
        if (args.length != 1) {
            System.err.println("usage: java ChangeLoader codebase_url");
            System.exit(-1);
        }
    
        String url = args[0];
        ClassLoader prevCl = Thread.currentThread().getContextClassLoader();
    
        // Create class loader using given codebase
        // Use prevCl as parent to maintain current visibility
        ClassLoader urlCl = URLClassLoader.newInstance(new URL[]{new URL(url)}, prevCl);
    
            try {
            // Save class loader so that we can restore later
                Thread.currentThread().setContextClassLoader(urlCl);
    
            // Expect that environment properties are in
            // application resource file found at "url"
            Context ctx = new InitialContext();
    
            System.out.println(ctx.lookup("tutorial/report.txt"));
    
            // Close context when no longer needed
            ctx.close();
        } catch (NamingException e) {
            e.printStackTrace();
            } finally {
                // Restore
                Thread.currentThread().setContextClassLoader(prevCl);
            }
        }
    }
    

提交回复
热议问题