安全地将包导出到 Java 个模块

Securely Export Packages to Java Modules

我在回答 问题时,我建议使用 exports to 语法来防止外部使用者访问旨在供模块之间内部使用的代码。

但进一步思考,模块实现的唯一真正的安全检查是它与名称相匹配。考虑这个我正在实现两个模块的例子:

module a {
    exports unsafe to b
}

module b {
    requires a
}

unsafe 包含暴露的代码是不安全的。有什么方法可以安全地将其导出到内部模块而不将它们暴露在外部?

在上面的示例中,流氓实体可以简单地将其模块命名为 b 并获得对代码的访问权限(不安全)。 JLS 似乎没有说明任何可以阻止它的内容。

模块散列为 shall work in your case. Though I personally like the description and the example from the JMOD tool 直接回答了您的问题:

With the --hash-modules option or the jmod hash command, you can, in each module's descriptor, record hashes of the content of the modules that are allowed to depend upon it, thus "tying" together these modules.

This lets you to allow a package to be exported to one or more specifically-named modules and to no others through qualified exports. The runtime verifies if the recorded hash of a module matches the one resolved at run time; if not, the runtime returns an error.