Home > Java > javaTutorial > body text

Java Module Import Feature

DDD
Release: 2024-10-05 06:12:30
Original
568 people have browsed it

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)


Copy after login

//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))));
  }

}


Copy after login

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!

source:dev.to
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!