如何通过class in Java 9获取模块名称?

How to get module name by class in Java 9?

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

模块 A 包含 class:

public class ClassA {

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

模块 B 包含 class:

public class ClassB {

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

怎么做?

得到一个Module by a Class in Java9, you can use the getModule()

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

并在 Module class 上进一步 getName 以获取模块的名称

String moduleName = module.getName();

需要注意的一点(不是在您的情况下,因为您使用的是命名模块)是 getModule returns 这个模块class 或接口是的成员。

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