3

Given some package foo.bar, how do I find which module does it belong to?

For example, package java.util belongs to module java.base. I can verify it by typing in jdeps -m java.base and by going through the long output. This however assumes my prior knowledge that package java.util belongs to module java.base.

How can I verify which module does the package belong to?

Avaldor
  • 317
  • 2
  • 8
  • Modules export packages, please see here: http://openjdk.java.net/jeps/261 – Avaldor Jul 27 '21 at 08:58
  • Huh interesting. I was thinking that since I can declare my own `java.util` package in my own module, the question of "which module does `java.util` belong to" isn't well defined. But after trying it out, I realised that I can't do that anymore in Java 9+. TIL – Sweeper Jul 27 '21 at 09:10
  • What is the actual use case for this specifically? I mean you can generally perform `jdeps` over a complete application too, so your prior knowledge need not be scoped. – Naman Jul 27 '21 at 15:14
  • 3
    @Sweeper you could never define your own `java.util` package. All qualified names starting with `java.` were reserved even before Java 9. For other non-reserved names, you still can define packages with the same name but different class loaders, as long as they belong to the unnamed module of either loader or to different module layers without a parent-child relationship. – Holger Jul 27 '21 at 18:33
  • 1
    @user16320675 changing the contents of the `java.util` package is entirely different to creating a different package with the same name at runtime. The modified `java.util` package would still belong to the `java.base` module. – Holger Aug 04 '21 at 16:57

1 Answers1

1

Is this what you want?

Optional<Module> found = ModuleLayer
        .boot()
        .modules()
        .stream()
        .filter(module -> module.getPackages().contains("java.util"))
        .findFirst();
ZhekaKozlov
  • 36,558
  • 20
  • 126
  • 155