java - 如何在 Java 9 中按类获取模块名称?

标签 java java-9 java-module

如何在 Java 9 中按类获取模块名称?例如,让我们考虑以下情况。有两个命名模块 - ModuleA 和 ModuleB。 ModuleA 对 ModuleB 一无所知。 ModuleB 需要 ModuleA。

ModuleA 包含类:

public class ClassA {

    public void printModuleName(Class klass) {
       //how to get here name of the module that contains klass?
    }
}

ModuleB 包含类:

public class ClassB {

    public void doIt() {
        ClassA objectA = new ClassA();
        objectA.printModuleName(ClassB.class);
    }
}

怎么做?

最佳答案

获取 Module Class 在 Java9 中,您可以使用 getModule()

Module module = com.foo.bar.YourClass.class.getModule();

和进一步getNameModule 类上获取模块的名称

String moduleName = module.getName();

需要注意的一点(不是在您的情况下,因为您使用的是命名模块)是 getModule 返回此类或接口(interface)所属的模块的。

  • If this class represents an array type then this method returns the Module for the element type.
  • If this class represents a primitive type or void, then the Module object for the java.base module is returned.
  • If this class is in an unnamed module then the unnamed Module of the class loader for this class is returned.

关于java - 如何在 Java 9 中按类获取模块名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46267150/

相关文章:

java - 缺少 "ice:column"的开始标记

java - java 中的 Entry<K,V> 数组如何工作?

java - hibernate 、Java 9 和 SystemException

java - JPMS 是否支持来自 META-INF/services 的自动模块服务?

java - 如何获取 Gradle Artifact 转换的输出?

java - 声明时初始化变量值

java - Hadoop DistributedCache 已弃用 - 首选 API 是什么?

performance-testing - Java 9的HashMap性能是否比Java 8低25%?

java - 如何解决java9中的模块读取包错误

java - 如何定义对未知模块的合格导出?