简体   繁体   中英

How to get module name by class in Java 9?

How to get module name by class in Java 9? For example, let's consider the following situation. There are two named modules - ModuleA and ModuleB. ModuleA knows nothing about ModuleB. ModuleB requires ModuleA.

ModuleA contains class:

public class ClassA {

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

ModuleB contains class:

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()

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

and further getName on the Module class to fetch the name of the 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM