1 /*
2 * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25 package java.lang;
26
27 import java.lang.module.Configuration;
28 import java.lang.module.ModuleReference;
29 import java.net.URI;
30
31 /**
32 * A NamedPackage represents a package by name in a specific module.
33 *
34 * A class loader will automatically create NamedPackage for each
35 * package when a class is defined. Package object is lazily
36 * defined until Class::getPackage, Package::getPackage(s), or
37 * ClassLoader::getDefinedPackage(s) method is called.
38 *
39 * NamedPackage allows ClassLoader to keep track of the runtime
40 * packages with minimal footprint and avoid constructing Package
41 * object.
42 */
43 class NamedPackage {
44 private final String name;
45 private final Module module;
46
47 NamedPackage(String pn, Module module) {
48 if (pn.isEmpty() && module.isNamed()) {
49 throw new InternalError("unnamed package in " + module);
50 }
51 this.name = pn.intern();
52 this.module = module;
53 }
54
55 /**
56 * Returns the name of this package.
57 */
58 String packageName() {
59 return name;
60 }
61
62 /**
63 * Returns the module of this named package.
64 */
65 Module module() {
66 return module;
67 }
68
69 /**
70 * Returns the location of the module if this named package is in
71 * a named module; otherwise, returns null.
72 */
73 URI location() {
74 if (module.isNamed() && module.getLayer() != null) {
75 Configuration cf = module.getLayer().configuration();
76 ModuleReference mref
77 = cf.findModule(module.getName()).get().reference();
78 return mref.location().orElse(null);
79 }
80 return null;
81 }
82
83 /**
84 * Creates a Package object of the given name and module.
85 */
86 static Package toPackage(String name, Module module) {
87 return new Package(name, module);
88 }
89 }
90