在运行时通过filepath直接导入.jar文件

时间:2021-01-23 18:04:22

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

这是一个“出于好奇”的问题。我熟悉在IDE(NetBeans,Eclipse)中设置用户库并通过类似的东西将它们导入程序

import com.mongodb; 

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

有没有办法直接导入库的jar文件?就像是

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.

再一次,这只是一种好奇心。我理解这与大多数惯例不符,但我正在考虑将来快速开发原型,我想知道这是否是在开发周期中节省一些时间的可行选择。

2 个解决方案

#1


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).

我们的想法是,您只使用Java导入包,而不是整个JAR文件。 (实际上你也可以使用import static导入静态类成员,但这是一个不同的主题)。

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.

其中lib / *表示从你的awesome-app.jar旁边的lib文件夹中“导入所有东西”。

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

请参阅此处了解如何将通配符与-cp参数一起使用。

#2


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.

使用奇怪的语法和所有这些都不可能完全相同,但是自定义类加载器可以在运行时加载jar文件。另见这个问题。

#1


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).

我们的想法是,您只使用Java导入包,而不是整个JAR文件。 (实际上你也可以使用import static导入静态类成员,但这是一个不同的主题)。

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.

其中lib / *表示从你的awesome-app.jar旁边的lib文件夹中“导入所有东西”。

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

请参阅此处了解如何将通配符与-cp参数一起使用。

#2


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.

使用奇怪的语法和所有这些都不可能完全相同,但是自定义类加载器可以在运行时加载jar文件。另见这个问题。