Search code examples
javaclassloader

Java import, without CLASSPATH


Is there a way to import other classes in Java without adding them to the classpath? Something like "import C:/dir/file.jar"?


Solution

  • You can't import a jar file just by changing the "import". But you can using the class loader. See How to load a jar file at runtime

    File file  = new File("C:\\dir\\file.jar");
    URL url = file.toURL();  
    ClassLoader classLoader = new URLClassLoader( new URL[]{ file.toURL() } );
    Class cls = classLoader.loadClass("mypackage.myclass");