Search code examples
javalinuximport-libraries

Importing .jar file directly via filepath at runtime


This is a "out of curiosity" question. I'm familiar with setting up user libraries in IDEs (NetBeans, Eclipse) and importing them to programs via something like

import com.mongodb; 

Is there a way to import a jar file for a library directly though? Something like

import C:/lib/mongodb/mongo-java-driver-2.12.2.jar;

or perhaps

import /libs/mongodb/;    // for linux, where /libs/ is a softlink

Again, this is a mere curiosity. I understand that this goes against most conventions, but I'm looking at rapidly developing prototypes in the future and I was wondering if this is a viable option for saving some time in the development cycle.


Solution

  • The idea is, that you only import packages in Java, not whole JAR files. (Actually you can also import static class members, using import static but that's a different topic).

    If you really need, you can just import the all classes from a package using the simple notation like:

    import com.mongodb.*; // This will import all classes from "com.mongodb" package
    

    And then execute your application like this:

    java.exe -cp "your-awesome-app.jar;lib/*"
    

    where lib/* means "import everything" from the lib folder that lies next to your-awesome-app.jar.

    See here on how to use wildcards with -cp parameter.