[英]How to get module name by class in Java 9?
How to get module name by class in Java 9? 如何在Java 9中按类获取模块名称? For example, let's consider the following situation. 例如,让我们考虑以下情况。 There are two named modules - ModuleA and ModuleB. 有两个命名模块 - ModuleA和ModuleB。 ModuleA knows nothing about ModuleB. ModuleA对ModuleB一无所知。 ModuleB requires ModuleA. ModuleB需要ModuleA。
ModuleA contains class: ModuleA包含类:
public class ClassA {
public void printModuleName(Class klass) {
//how to get here name of the module that contains klass?
}
}
ModuleB contains class: ModuleB包含类:
public class ClassB {
public void doIt() {
ClassA objectA = new ClassA();
objectA.printModuleName(ClassB.class);
}
}
How to do it? 怎么做?
To get a Module
by a Class
in Java9, you can use the getModule()
要在Java9中通过Class
获取Module
,可以使用getModule()
Module module = com.foo.bar.YourClass.class.getModule();
and further getName
on the Module
class to fetch the name of the module 并在Module
类上进一步getName
以获取Module
的名称
String moduleName = module.getName();
An observable point to note (not in your case as you're using named modules) is that the getModule
returns the module that this class or interface is a member of. 一个可观察的注意事项(在您使用命名模块时不是这种情况)是getModule
返回此类或接口所属的模块。
- If this class represents an array type then this method returns the Module for the element type. 如果此类表示数组类型,则此方法返回元素类型的Module。
- If this class represents a primitive type or void, then the Module object for the
java.base
module is returned. 如果此类表示基本类型或void,则返回java.base
模块的Module对象。- If this class is in an unnamed module then the unnamed Module of the class loader for this class is returned. 如果此类位于未命名的模块中,则返回此类的类加载器的未命名模块。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.