Home  >  Article  >  Java  >  Java Module Import Feature

Java Module Import Feature

DDD
DDDOriginal
2024-10-05 06:12:30529browse

Java  Module Import Feature

Java 23 introduces two new preview features: Module Import Declarations (Preview) and Automatic Module Import in Implicitly Declared Classes. These should not be used in production code, as they are still subject to change.

1. Module Import Declarations (Preview) - JEP 476
With the release of Java 23, we are now able to import complete modules in our code. This means that we can import all the classes in the packages exported by that module.

For example, we can import the complete java.base module and use classes like List, Set, Map, and Collectors without having to make individual import statements for each class. This can be done by using the "import module" syntax:


//Old style:
import java.util.Map;                   // or import java.util.*;
import java.util.function.Function;     // or import java.util.function.*;
import java.util.stream.Collectors;     // or import java.util.stream.*;
import java.util.stream.Stream;         // (can be removed)



//New Style:
import module java.base;

public class MyExamCloud {

  public static Map<Character, List<String>> groupByFirstLetter(String...values) {
    return Stream.of(values).collect(
      Collectors.groupingBy(s -> Character.toUpperCase(s.charAt(0))));
  }

}


Note that the importing class does not need to be in a module to use this syntax.

Ambiguous class names may arise if there are two imported classes with the same name. To resolve this, we need to specify the desired class directly in an import statement.

Additionally, when one module transitively imports another module, we can use all the classes in the exported packages of the transitively imported module without any explicit imports. For example, the java.sql module transitively imports the java.xml module, so we can use classes from java.xml without needing to import them explicitly.

2. Automatic Module Import in Implicitly Declared Classes
In Java 23, implicitly declared classes will automatically import the complete java.base module.

The above is the detailed content of Java Module Import Feature. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn