Learnitweb

requires static in Java

1. Introduction

The requires static is used to define compile-time dependencies. The compile-time dependencies are required only during the compile time.

Sometimes our code may have a dependency on another module, but only at the compile-time. The users of our code may not want to include the unwanted module on which our module depends. In such case we declare compile-time dependencies using requires static.

If a dependency is required only at compile-time but optional at run-time, such type of dependency is called optional dependency.

module myModule {
    requires static optionalModule;
}

The static keyword here refers that the dependency check (here module optionalModule) is required at compile time but not at runtime.

2. Use cases of optional dependency

Sometimes when we develop a library, we have dependencies on other modules. But such dependencies may not be required at run-time. For example, if a certain type of connection is not available at run-time, create another type of connection.

For example, if MySql is available use it, else use Oracle Database.

3. Example of requires static

module moduleB {
	requires moduleA;
}

Here, moduleA is required at compile time as well as run-time. moduleA is not an optional dependency.

module moduleB {
	requires static moduleA;
}

Here, moduleA is required at compile-time but not at run-time. moduleA is an optional dependency. So if moduleA is not available at run-time, there will be no error.

4. Conclusion

The requires static is used to define compile-time dependencies. This is good to know if you are developing your own library.