如何在未模块化的应用程序中使用模块化的jar?

问题描述 投票:1回答:2

在不同的地方,我看到了以下信息:未命名模块中的类被允许读取模块路径上的导出包。

在目录src / calculators中,我有module-info.java文件:

module calculators {
  exports calculators;
}

在目录src / calculators / calculators中,我有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

为什么?应用程序类是否应该能够读取导出的包?我在这里错了吗?

java java-module unnamed-module
2个回答
0
投票

简短回答

您的最后一个命令行应该是:

javac --class-path calculators.jar  *.java

而不是:

javac --module-path calculators.jar  *.java

为什么?

如果正在编译非模块化应用程序,则不应使用--module-path选项,而应使用--class-path(或更短的版本:-cp)。

[请记住,模块化JAR仍然像常规JAR一样工作。它仅包含有关模块化应用程序的更多信息。


0
投票

由于您的应用程序代码不是模块,因此环境中没有任何内容告诉Java解析calculators模块。即使将JAR文件放在模块路径上,这也导致找不到类。如果要继续使用库的模块路径,则需要使用:

javac --module-path calculators.jar --add-modules calculators <rest-of-command>

注意--add-modules calculators参数。这使calculators模块成为根,迫使其及其所有requires依赖关系进入模块图。

© www.soinside.com 2019 - 2024. All rights reserved.