如何在 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();
和进一步getName
在 Module
类上获取模块的名称
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/