在不同的地方,我看到了以下信息:中的类、未命名的模块允许读取模块路径上导出的包。
在src/calculators目录中,我有一个模块-info.java文件:
module calculators {
exports calculators;
}在目录src/计算器/计算器中,我有一个InterestCalculator.java文件:
package calculators;
public interface InterestCalculator {
public double calculate(double principle, double rate, double time);
}我使用以下命令编译了该模块:
java --module-source-path src --module calculators -d out然后,我使用以下命令打包了编译后的模块:
jar --create --file calculators.jar -C out/calculators/ .现在,我的非模块化应用程序有以下类(在相同的dir中):
import calculators.InterestCalculator;
class SimpleInterestCalculator implements InterestCalculator {
public double calculate(double principle, double rate, double time){
return principle * rate * time;
}
}import calculators.InterestCalculator;
class Main {
public static void main(String[] args) {
InterestCalculator interestCalculator = new SimpleInterestCalculator();
}
}当我使用以下命令使用模块编译我的应用程序时:
javac --module-path calculators.jar *.java我发现了一个错误:
Main.java:1: error: package calculators is not visible
import calculators.InterestCalculator;
^
(package calculators is declared in module calculators, which is not in the module graph)
SimpleInterestCalculator.java:1: error: package calculators is not visible
import calculators.InterestCalculator;
^
(package calculators is declared in module calculators, which is not in the module graph)
2 errors为什么?应用程序类不应该能够读取导出的包吗?我在这里做错什么了?
发布于 2020-03-07 15:10:26
由于您的应用程序代码不是一个模块,所以环境中没有任何东西要求Java解析calculators模块。这将导致尽管将JAR文件放置在模块路径上,但仍然找不到类。如果要继续为库使用模块路径,则需要使用:
javac --module-path calculators.jar --add-modules calculators <rest-of-command>注意--add-modules calculators参数。这使得calculators模块成为根,迫使它和它的所有requires依赖关系(过渡)进入模块图。如果您的应用程序是模块化的:
module app {
requires calculators;
}然后您将不再需要--add-modules,因为app模块将是根用户,而它需要calculators模块。
发布于 2020-03-07 14:36:56
短答案
最后一个命令行应该是:
javac --class-path calculators.jar *.java而不是:
javac --module-path calculators.jar *.java为什么?
如果您正在编译一个非模块化的应用程序,则不应该使用--module-path选项,而应该使用--class-path (或更短的版本:-cp)。
记住,模块化的JAR仍然像普通的JAR一样工作。它只包含一些模块应用程序的更多信息。
https://stackoverflow.com/questions/60578416
复制相似问题