Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 283
Pavel_K Avatar asked Sep 17 '17 17:09

Pavel_K


People also ask

How do you get a module in Java?

The getModule() method of java. lang. Class class is used to get the module of this entity. This entity can be a class, an array, an interface, etc.

How do you name a module in Java?

A Java module name follows the same naming rules as Java packages. However, you should not use underscores ( _ ) in module names (or package names, class names, method names, variable names etc.) from Java 9 and forward, because Java wants to use underscore as a reserved identifier in the future.

What is the base module of all the modules in Java 9?

java. base is known as the "mother of Java 9 modules." In the following image, you can see the modular aspects of the system and can probably make the leap to understand how a modularized JDK means that you can also modularize your own applications. This is only a few of the 98 platform modules.

What is module name in Java project?

These modules are split into four major groups: java, javafx, jdk, and Oracle. java modules are the implementation classes for the core SE Language Specification. javafx modules are the FX UI libraries. Anything needed by the JDK itself is kept in the jdk modules.


1 Answers

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.
like image 189
Naman Avatar answered Nov 08 '22 16:11

Naman