1

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.

Kyte
  • 834
  • 2
  • 12
  • 27
  • 1
    don't see what time you are trying to save? you can't write an import statement directly to a file, but you can add any jars you want to the java command line. – jtahlborn May 22 '14 at 12:41
  • This is not possible. What would be the benefit? There are multiple problems with that. 1) This is a fixed path, it only works either on windows or linux 2) the user can't replace the implementation with a different implementation (unless he renames the jar) 3) You are fixed on a version 4) You would still need to import the classes, e.g. `import com.mongodb.Query;` – Absurd-Mind May 22 '14 at 12:44
  • thanks for the quick answers. The idea would be to not type out the import on the command line every time I wanted to compile and run – Kyte May 22 '14 at 12:49
  • @Kyte than you should take a look into build scripts/environments like maven, ant, gradle, buildr, ivy, and maybe Makefiles. – Absurd-Mind May 22 '14 at 13:38
  • @Absurd-Mind, this is definitely what I will do in the future – Kyte May 22 '14 at 13:39

2 Answers2

1

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.

Community
  • 1
  • 1
npe
  • 15,395
  • 1
  • 56
  • 55
0

It's not possible to do exactly like that, with the weird syntax and all, but a custom classloader can load jar-files at run time. Also see this question.

Community
  • 1
  • 1
Martin Wickman
  • 19,662
  • 12
  • 82
  • 106