How to get module name by class in Java 9?

How to get module name by class in Java 9? For example, consider the following situation. There are two named modules - ModuleA and ModuleB. ModuleA does not know anything about ModuleB. ModuleB requires ModuleA.

ModuleA contains the class:

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

ModuleB contains a class:

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

How to do it?

+5
source share
1 answer

To get Module using Class in Java9, you can use getModule()

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

and then getName in the Module class to retrieve the module name

 String moduleName = module.getName(); 

A notable note (not in your case when you use named modules) is that getModule returns a module of which this class or interface is a member.

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

Source: https://habr.com/ru/post/1271887/


All Articles