1 /* 2 * Copyright (c) 2013, 2020, Oracle and/or its affiliates. All rights reserved. 3 * Copyright (c) 2019, Azul Systems, Inc. All rights reserved. 4 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 5 * 6 * This code is free software; you can redistribute it and/or modify it 7 * under the terms of the GNU General Public License version 2 only, as 8 * published by the Free Software Foundation. Oracle designates this 9 * particular file as subject to the "Classpath" exception as provided 10 * by Oracle in the LICENSE file that accompanied this code. 11 * 12 * This code is distributed in the hope that it will be useful, but WITHOUT 13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 14 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 15 * version 2 for more details (a copy is included in the LICENSE file that 16 * accompanied this code). 17 * 18 * You should have received a copy of the GNU General Public License version 19 * 2 along with this work; if not, write to the Free Software Foundation, 20 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 21 * 22 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 23 * or visit www.oracle.com if you need additional information or have any 24 * questions. 25 */ 26 27 package java.lang; 28 29 import java.io.InputStream; 30 import java.io.IOException; 31 import java.io.UncheckedIOException; 32 import java.io.File; 33 import java.lang.reflect.Constructor; 34 import java.lang.reflect.InvocationTargetException; 35 import java.net.URL; 36 import java.security.AccessController; 37 import java.security.AccessControlContext; 38 import java.security.CodeSource; 39 import java.security.PrivilegedAction; 40 import java.security.ProtectionDomain; 41 import java.security.cert.Certificate; 42 import java.util.ArrayList; 43 import java.util.Collections; 44 import java.util.Enumeration; 45 import java.util.HashMap; 46 import java.util.Map; 47 import java.util.NoSuchElementException; 48 import java.util.Objects; 49 import java.util.Set; 50 import java.util.Spliterator; 51 import java.util.Spliterators; 52 import java.util.WeakHashMap; 53 import java.util.concurrent.ConcurrentHashMap; 54 import java.util.function.Supplier; 55 import java.util.stream.Stream; 56 import java.util.stream.StreamSupport; 57 58 import jdk.internal.loader.BootLoader; 59 import jdk.internal.loader.BuiltinClassLoader; 60 import jdk.internal.loader.ClassLoaders; 61 import jdk.internal.loader.NativeLibrary; 62 import jdk.internal.loader.NativeLibraries; 63 import jdk.internal.perf.PerfCounter; 64 import jdk.internal.misc.Unsafe; 65 import jdk.internal.misc.VM; 66 import jdk.internal.reflect.CallerSensitive; 67 import jdk.internal.reflect.Reflection; 68 import jdk.internal.util.StaticProperty; 69 import sun.reflect.misc.ReflectUtil; 70 import sun.security.util.SecurityConstants; 71 72 /** 73 * A class loader is an object that is responsible for loading classes. The 74 * class {@code ClassLoader} is an abstract class. Given the <a 75 * href="#binary-name">binary name</a> of a class, a class loader should attempt to 76 * locate or generate data that constitutes a definition for the class. A 77 * typical strategy is to transform the name into a file name and then read a 78 * "class file" of that name from a file system. 79 * 80 * <p> Every {@link java.lang.Class Class} object contains a {@link 81 * Class#getClassLoader() reference} to the {@code ClassLoader} that defined 82 * it. 83 * 84 * <p> {@code Class} objects for array classes are not created by class 85 * loaders, but are created automatically as required by the Java runtime. 86 * The class loader for an array class, as returned by {@link 87 * Class#getClassLoader()} is the same as the class loader for its element 88 * type; if the element type is a primitive type, then the array class has no 89 * class loader. 90 * 91 * <p> Applications implement subclasses of {@code ClassLoader} in order to 92 * extend the manner in which the Java virtual machine dynamically loads 93 * classes. 94 * 95 * <p> Class loaders may typically be used by security managers to indicate 96 * security domains. 97 * 98 * <p> In addition to loading classes, a class loader is also responsible for 99 * locating resources. A resource is some data (a "{@code .class}" file, 100 * configuration data, or an image for example) that is identified with an 101 * abstract '/'-separated path name. Resources are typically packaged with an 102 * application or library so that they can be located by code in the 103 * application or library. In some cases, the resources are included so that 104 * they can be located by other libraries. 105 * 106 * <p> The {@code ClassLoader} class uses a delegation model to search for 107 * classes and resources. Each instance of {@code ClassLoader} has an 108 * associated parent class loader. When requested to find a class or 109 * resource, a {@code ClassLoader} instance will usually delegate the search 110 * for the class or resource to its parent class loader before attempting to 111 * find the class or resource itself. 112 * 113 * <p> Class loaders that support concurrent loading of classes are known as 114 * <em>{@linkplain #isRegisteredAsParallelCapable() parallel capable}</em> class 115 * loaders and are required to register themselves at their class initialization 116 * time by invoking the {@link 117 * #registerAsParallelCapable ClassLoader.registerAsParallelCapable} 118 * method. Note that the {@code ClassLoader} class is registered as parallel 119 * capable by default. However, its subclasses still need to register themselves 120 * if they are parallel capable. 121 * In environments in which the delegation model is not strictly 122 * hierarchical, class loaders need to be parallel capable, otherwise class 123 * loading can lead to deadlocks because the loader lock is held for the 124 * duration of the class loading process (see {@link #loadClass 125 * loadClass} methods). 126 * 127 * <h2> <a id="builtinLoaders">Run-time Built-in Class Loaders</a></h2> 128 * 129 * The Java run-time has the following built-in class loaders: 130 * 131 * <ul> 132 * <li><p>Bootstrap class loader. 133 * It is the virtual machine's built-in class loader, typically represented 134 * as {@code null}, and does not have a parent.</li> 135 * <li><p>{@linkplain #getPlatformClassLoader() Platform class loader}. 136 * The platform class loader is responsible for loading the 137 * <em>platform classes</em>. Platform classes include Java SE platform APIs, 138 * their implementation classes and JDK-specific run-time classes that are 139 * defined by the platform class loader or its ancestors. 140 * The platform class loader can be used as the parent of a {@code ClassLoader} 141 * instance. 142 * <p> To allow for upgrading/overriding of modules defined to the platform 143 * class loader, and where upgraded modules read modules defined to class 144 * loaders other than the platform class loader and its ancestors, then 145 * the platform class loader may have to delegate to other class loaders, 146 * the application class loader for example. 147 * In other words, classes in named modules defined to class loaders 148 * other than the platform class loader and its ancestors may be visible 149 * to the platform class loader. </li> 150 * <li><p>{@linkplain #getSystemClassLoader() System class loader}. 151 * It is also known as <em>application class loader</em> and is distinct 152 * from the platform class loader. 153 * The system class loader is typically used to define classes on the 154 * application class path, module path, and JDK-specific tools. 155 * The platform class loader is the parent or an ancestor of the system class 156 * loader, so the system class loader can load platform classes by delegating 157 * to its parent.</li> 158 * </ul> 159 * 160 * <p> Normally, the Java virtual machine loads classes from the local file 161 * system in a platform-dependent manner. 162 * However, some classes may not originate from a file; they may originate 163 * from other sources, such as the network, or they could be constructed by an 164 * application. The method {@link #defineClass(String, byte[], int, int) 165 * defineClass} converts an array of bytes into an instance of class 166 * {@code Class}. Instances of this newly defined class can be created using 167 * {@link Class#newInstance Class.newInstance}. 168 * 169 * <p> The methods and constructors of objects created by a class loader may 170 * reference other classes. To determine the class(es) referred to, the Java 171 * virtual machine invokes the {@link #loadClass loadClass} method of 172 * the class loader that originally created the class. 173 * 174 * <p> For example, an application could create a network class loader to 175 * download class files from a server. Sample code might look like: 176 * 177 * <blockquote><pre> 178 * ClassLoader loader = new NetworkClassLoader(host, port); 179 * Object main = loader.loadClass("Main", true).newInstance(); 180 * . . . 181 * </pre></blockquote> 182 * 183 * <p> The network class loader subclass must define the methods {@link 184 * #findClass findClass} and {@code loadClassData} to load a class 185 * from the network. Once it has downloaded the bytes that make up the class, 186 * it should use the method {@link #defineClass defineClass} to 187 * create a class instance. A sample implementation is: 188 * 189 * <blockquote><pre> 190 * class NetworkClassLoader extends ClassLoader { 191 * String host; 192 * int port; 193 * 194 * public Class findClass(String name) { 195 * byte[] b = loadClassData(name); 196 * return defineClass(name, b, 0, b.length); 197 * } 198 * 199 * private byte[] loadClassData(String name) { 200 * // load the class data from the connection 201 * . . . 202 * } 203 * } 204 * </pre></blockquote> 205 * 206 * <h3> <a id="binary-name">Binary names</a> </h3> 207 * 208 * <p> Any class name provided as a {@code String} parameter to methods in 209 * {@code ClassLoader} must be a binary name as defined by 210 * <cite>The Java Language Specification</cite>. 211 * 212 * <p> Examples of valid class names include: 213 * <blockquote><pre> 214 * "java.lang.String" 215 * "javax.swing.JSpinner$DefaultEditor" 216 * "java.security.KeyStore$Builder$FileBuilder$1" 217 * "java.net.URLClassLoader$3$1" 218 * </pre></blockquote> 219 * 220 * <p> Any package name provided as a {@code String} parameter to methods in 221 * {@code ClassLoader} must be either the empty string (denoting an unnamed package) 222 * or a fully qualified name as defined by 223 * <cite>The Java Language Specification</cite>. 224 * 225 * @jls 6.7 Fully Qualified Names 226 * @jls 13.1 The Form of a Binary 227 * @see #resolveClass(Class) 228 * @since 1.0 229 * @revised 9 230 * @spec JPMS 231 */ 232 public abstract class ClassLoader { 233 234 private static native void registerNatives(); 235 static { 236 registerNatives(); 237 } 238 239 // The parent class loader for delegation 240 // Note: VM hardcoded the offset of this field, thus all new fields 241 // must be added *after* it. 242 private final ClassLoader parent; 243 244 // class loader name 245 private final String name; 246 247 // the unnamed module for this ClassLoader 248 private final Module unnamedModule; 249 250 // a string for exception message printing 251 private final String nameAndId; 252 253 /** 254 * Encapsulates the set of parallel capable loader types. 255 */ 256 private static class ParallelLoaders { 257 private ParallelLoaders() {} 258 259 // the set of parallel capable loader types 260 private static final Set<Class<? extends ClassLoader>> loaderTypes = 261 Collections.newSetFromMap(new WeakHashMap<>()); 262 static { 263 synchronized (loaderTypes) { loaderTypes.add(ClassLoader.class); } 264 } 265 266 /** 267 * Registers the given class loader type as parallel capable. 268 * Returns {@code true} is successfully registered; {@code false} if 269 * loader's super class is not registered. 270 */ 271 static boolean register(Class<? extends ClassLoader> c) { 272 synchronized (loaderTypes) { 273 if (loaderTypes.contains(c.getSuperclass())) { 274 // register the class loader as parallel capable 275 // if and only if all of its super classes are. 276 // Note: given current classloading sequence, if 277 // the immediate super class is parallel capable, 278 // all the super classes higher up must be too. 279 loaderTypes.add(c); 280 return true; 281 } else { 282 return false; 283 } 284 } 285 } 286 287 /** 288 * Returns {@code true} if the given class loader type is 289 * registered as parallel capable. 290 */ 291 static boolean isRegistered(Class<? extends ClassLoader> c) { 292 synchronized (loaderTypes) { 293 return loaderTypes.contains(c); 294 } 295 } 296 } 297 298 // Maps class name to the corresponding lock object when the current 299 // class loader is parallel capable. 300 // Note: VM also uses this field to decide if the current class loader 301 // is parallel capable and the appropriate lock object for class loading. 302 private final ConcurrentHashMap<String, Object> parallelLockMap; 303 304 // Maps packages to certs 305 private final ConcurrentHashMap<String, Certificate[]> package2certs; 306 307 // Shared among all packages with unsigned classes 308 private static final Certificate[] nocerts = new Certificate[0]; 309 310 // The classes loaded by this class loader. The only purpose of this table 311 // is to keep the classes from being GC'ed until the loader is GC'ed. 312 private final ArrayList<Class<?>> classes = new ArrayList<>(); 313 314 // The "default" domain. Set as the default ProtectionDomain on newly 315 // created classes. 316 private final ProtectionDomain defaultDomain = 317 new ProtectionDomain(new CodeSource(null, (Certificate[]) null), 318 null, this, null); 319 320 // Invoked by the VM to record every loaded class with this loader. 321 void addClass(Class<?> c) { 322 synchronized (classes) { 323 classes.add(c); 324 } 325 } 326 327 // The packages defined in this class loader. Each package name is 328 // mapped to its corresponding NamedPackage object. 329 // 330 // The value is a Package object if ClassLoader::definePackage, 331 // Class::getPackage, ClassLoader::getDefinePackage(s) or 332 // Package::getPackage(s) method is called to define it. 333 // Otherwise, the value is a NamedPackage object. 334 private final ConcurrentHashMap<String, NamedPackage> packages 335 = new ConcurrentHashMap<>(); 336 337 /* 338 * Returns a named package for the given module. 339 */ 340 private NamedPackage getNamedPackage(String pn, Module m) { 341 NamedPackage p = packages.get(pn); 342 if (p == null) { 343 p = new NamedPackage(pn, m); 344 345 NamedPackage value = packages.putIfAbsent(pn, p); 346 if (value != null) { 347 // Package object already be defined for the named package 348 p = value; 349 // if definePackage is called by this class loader to define 350 // a package in a named module, this will return Package 351 // object of the same name. Package object may contain 352 // unexpected information but it does not impact the runtime. 353 // this assertion may be helpful for troubleshooting 354 assert value.module() == m; 355 } 356 } 357 return p; 358 } 359 360 private static Void checkCreateClassLoader() { 361 return checkCreateClassLoader(null); 362 } 363 364 private static Void checkCreateClassLoader(String name) { 365 if (name != null && name.isEmpty()) { 366 throw new IllegalArgumentException("name must be non-empty or null"); 367 } 368 369 SecurityManager security = System.getSecurityManager(); 370 if (security != null) { 371 security.checkCreateClassLoader(); 372 } 373 return null; 374 } 375 376 private ClassLoader(Void unused, String name, ClassLoader parent) { 377 this.name = name; 378 this.parent = parent; 379 this.unnamedModule = new Module(this); 380 if (ParallelLoaders.isRegistered(this.getClass())) { 381 parallelLockMap = new ConcurrentHashMap<>(); 382 assertionLock = new Object(); 383 } else { 384 // no finer-grained lock; lock on the classloader instance 385 parallelLockMap = null; 386 assertionLock = this; 387 } 388 this.package2certs = new ConcurrentHashMap<>(); 389 this.nameAndId = nameAndId(this); 390 } 391 392 /** 393 * If the defining loader has a name explicitly set then 394 * '<loader-name>' @<id> 395 * If the defining loader has no name then 396 * <qualified-class-name> @<id> 397 * If it's built-in loader then omit `@<id>` as there is only one instance. 398 */ 399 private static String nameAndId(ClassLoader ld) { 400 String nid = ld.getName() != null ? "\'" + ld.getName() + "\'" 401 : ld.getClass().getName(); 402 if (!(ld instanceof BuiltinClassLoader)) { 403 String id = Integer.toHexString(System.identityHashCode(ld)); 404 nid = nid + " @" + id; 405 } 406 return nid; 407 } 408 409 /** 410 * Creates a new class loader of the specified name and using the 411 * specified parent class loader for delegation. 412 * 413 * @apiNote If the parent is specified as {@code null} (for the 414 * bootstrap class loader) then there is no guarantee that all platform 415 * classes are visible. 416 * 417 * @param name class loader name; or {@code null} if not named 418 * @param parent the parent class loader 419 * 420 * @throws IllegalArgumentException if the given name is empty. 421 * 422 * @throws SecurityException 423 * If a security manager exists and its 424 * {@link SecurityManager#checkCreateClassLoader()} 425 * method doesn't allow creation of a new class loader. 426 * 427 * @since 9 428 * @spec JPMS 429 */ 430 protected ClassLoader(String name, ClassLoader parent) { 431 this(checkCreateClassLoader(name), name, parent); 432 } 433 434 /** 435 * Creates a new class loader using the specified parent class loader for 436 * delegation. 437 * 438 * <p> If there is a security manager, its {@link 439 * SecurityManager#checkCreateClassLoader() checkCreateClassLoader} method 440 * is invoked. This may result in a security exception. </p> 441 * 442 * @apiNote If the parent is specified as {@code null} (for the 443 * bootstrap class loader) then there is no guarantee that all platform 444 * classes are visible. 445 * 446 * @param parent 447 * The parent class loader 448 * 449 * @throws SecurityException 450 * If a security manager exists and its 451 * {@code checkCreateClassLoader} method doesn't allow creation 452 * of a new class loader. 453 * 454 * @since 1.2 455 */ 456 protected ClassLoader(ClassLoader parent) { 457 this(checkCreateClassLoader(), null, parent); 458 } 459 460 /** 461 * Creates a new class loader using the {@code ClassLoader} returned by 462 * the method {@link #getSystemClassLoader() 463 * getSystemClassLoader()} as the parent class loader. 464 * 465 * <p> If there is a security manager, its {@link 466 * SecurityManager#checkCreateClassLoader() 467 * checkCreateClassLoader} method is invoked. This may result in 468 * a security exception. </p> 469 * 470 * @throws SecurityException 471 * If a security manager exists and its 472 * {@code checkCreateClassLoader} method doesn't allow creation 473 * of a new class loader. 474 */ 475 protected ClassLoader() { 476 this(checkCreateClassLoader(), null, getSystemClassLoader()); 477 } 478 479 /** 480 * Returns the name of this class loader or {@code null} if 481 * this class loader is not named. 482 * 483 * @apiNote This method is non-final for compatibility. If this 484 * method is overridden, this method must return the same name 485 * as specified when this class loader was instantiated. 486 * 487 * @return name of this class loader; or {@code null} if 488 * this class loader is not named. 489 * 490 * @since 9 491 * @spec JPMS 492 */ 493 public String getName() { 494 return name; 495 } 496 497 // package-private used by StackTraceElement to avoid 498 // calling the overrideable getName method 499 final String name() { 500 return name; 501 } 502 503 // -- Class -- 504 505 /** 506 * Loads the class with the specified <a href="#binary-name">binary name</a>. 507 * This method searches for classes in the same manner as the {@link 508 * #loadClass(String, boolean)} method. It is invoked by the Java virtual 509 * machine to resolve class references. Invoking this method is equivalent 510 * to invoking {@link #loadClass(String, boolean) loadClass(name, 511 * false)}. 512 * 513 * @param name 514 * The <a href="#binary-name">binary name</a> of the class 515 * 516 * @return The resulting {@code Class} object 517 * 518 * @throws ClassNotFoundException 519 * If the class was not found 520 */ 521 public Class<?> loadClass(String name) throws ClassNotFoundException { 522 return loadClass(name, false); 523 } 524 525 /** 526 * Loads the class with the specified <a href="#binary-name">binary name</a>. The 527 * default implementation of this method searches for classes in the 528 * following order: 529 * 530 * <ol> 531 * 532 * <li><p> Invoke {@link #findLoadedClass(String)} to check if the class 533 * has already been loaded. </p></li> 534 * 535 * <li><p> Invoke the {@link #loadClass(String) loadClass} method 536 * on the parent class loader. If the parent is {@code null} the class 537 * loader built into the virtual machine is used, instead. </p></li> 538 * 539 * <li><p> Invoke the {@link #findClass(String)} method to find the 540 * class. </p></li> 541 * 542 * </ol> 543 * 544 * <p> If the class was found using the above steps, and the 545 * {@code resolve} flag is true, this method will then invoke the {@link 546 * #resolveClass(Class)} method on the resulting {@code Class} object. 547 * 548 * <p> Subclasses of {@code ClassLoader} are encouraged to override {@link 549 * #findClass(String)}, rather than this method. </p> 550 * 551 * <p> Unless overridden, this method synchronizes on the result of 552 * {@link #getClassLoadingLock getClassLoadingLock} method 553 * during the entire class loading process. 554 * 555 * @param name 556 * The <a href="#binary-name">binary name</a> of the class 557 * 558 * @param resolve 559 * If {@code true} then resolve the class 560 * 561 * @return The resulting {@code Class} object 562 * 563 * @throws ClassNotFoundException 564 * If the class could not be found 565 */ 566 protected Class<?> loadClass(String name, boolean resolve) 567 throws ClassNotFoundException 568 { 569 synchronized (getClassLoadingLock(name)) { 570 // First, check if the class has already been loaded 571 Class<?> c = findLoadedClass(name); 572 if (c == null) { 573 long t0 = System.nanoTime(); 574 try { 575 if (parent != null) { 576 c = parent.loadClass(name, false); 577 } else { 578 c = findBootstrapClassOrNull(name); 579 } 580 } catch (ClassNotFoundException e) { 581 // ClassNotFoundException thrown if class not found 582 // from the non-null parent class loader 583 } 584 585 if (c == null) { 586 // If still not found, then invoke findClass in order 587 // to find the class. 588 long t1 = System.nanoTime(); 589 c = findClass(name); 590 591 // this is the defining class loader; record the stats 592 PerfCounter.getParentDelegationTime().addTime(t1 - t0); 593 PerfCounter.getFindClassTime().addElapsedTimeFrom(t1); 594 PerfCounter.getFindClasses().increment(); 595 } 596 } 597 if (resolve) { 598 resolveClass(c); 599 } 600 return c; 601 } 602 } 603 604 /** 605 * Loads the class with the specified <a href="#binary-name">binary name</a> 606 * in a module defined to this class loader. This method returns {@code null} 607 * if the class could not be found. 608 * 609 * @apiNote This method does not delegate to the parent class loader. 610 * 611 * @implSpec The default implementation of this method searches for classes 612 * in the following order: 613 * 614 * <ol> 615 * <li>Invoke {@link #findLoadedClass(String)} to check if the class 616 * has already been loaded.</li> 617 * <li>Invoke the {@link #findClass(String, String)} method to find the 618 * class in the given module.</li> 619 * </ol> 620 * 621 * @param module 622 * The module 623 * @param name 624 * The <a href="#binary-name">binary name</a> of the class 625 * 626 * @return The resulting {@code Class} object in a module defined by 627 * this class loader, or {@code null} if the class could not be found. 628 */ 629 final Class<?> loadClass(Module module, String name) { 630 synchronized (getClassLoadingLock(name)) { 631 // First, check if the class has already been loaded 632 Class<?> c = findLoadedClass(name); 633 if (c == null) { 634 c = findClass(module.getName(), name); 635 } 636 if (c != null && c.getModule() == module) { 637 return c; 638 } else { 639 return null; 640 } 641 } 642 } 643 644 /** 645 * Returns the lock object for class loading operations. 646 * For backward compatibility, the default implementation of this method 647 * behaves as follows. If this ClassLoader object is registered as 648 * parallel capable, the method returns a dedicated object associated 649 * with the specified class name. Otherwise, the method returns this 650 * ClassLoader object. 651 * 652 * @param className 653 * The name of the to-be-loaded class 654 * 655 * @return the lock for class loading operations 656 * 657 * @throws NullPointerException 658 * If registered as parallel capable and {@code className} is null 659 * 660 * @see #loadClass(String, boolean) 661 * 662 * @since 1.7 663 */ 664 protected Object getClassLoadingLock(String className) { 665 Object lock = this; 666 if (parallelLockMap != null) { 667 Object newLock = new Object(); 668 lock = parallelLockMap.putIfAbsent(className, newLock); 669 if (lock == null) { 670 lock = newLock; 671 } 672 } 673 return lock; 674 } 675 676 // Invoked by the VM after loading class with this loader. 677 private void checkPackageAccess(Class<?> cls, ProtectionDomain pd) { 678 final SecurityManager sm = System.getSecurityManager(); 679 if (sm != null) { 680 if (ReflectUtil.isNonPublicProxyClass(cls)) { 681 for (Class<?> intf: cls.getInterfaces()) { 682 checkPackageAccess(intf, pd); 683 } 684 return; 685 } 686 687 final String packageName = cls.getPackageName(); 688 if (!packageName.isEmpty()) { 689 AccessController.doPrivileged(new PrivilegedAction<>() { 690 public Void run() { 691 sm.checkPackageAccess(packageName); 692 return null; 693 } 694 }, new AccessControlContext(new ProtectionDomain[] {pd})); 695 } 696 } 697 } 698 699 /** 700 * Finds the class with the specified <a href="#binary-name">binary name</a>. 701 * This method should be overridden by class loader implementations that 702 * follow the delegation model for loading classes, and will be invoked by 703 * the {@link #loadClass loadClass} method after checking the 704 * parent class loader for the requested class. 705 * 706 * @implSpec The default implementation throws {@code ClassNotFoundException}. 707 * 708 * @param name 709 * The <a href="#binary-name">binary name</a> of the class 710 * 711 * @return The resulting {@code Class} object 712 * 713 * @throws ClassNotFoundException 714 * If the class could not be found 715 * 716 * @since 1.2 717 */ 718 protected Class<?> findClass(String name) throws ClassNotFoundException { 719 throw new ClassNotFoundException(name); 720 } 721 722 /** 723 * Finds the class with the given <a href="#binary-name">binary name</a> 724 * in a module defined to this class loader. 725 * Class loader implementations that support loading from modules 726 * should override this method. 727 * 728 * @apiNote This method returns {@code null} rather than throwing 729 * {@code ClassNotFoundException} if the class could not be found. 730 * 731 * @implSpec The default implementation attempts to find the class by 732 * invoking {@link #findClass(String)} when the {@code moduleName} is 733 * {@code null}. It otherwise returns {@code null}. 734 * 735 * @param moduleName 736 * The module name; or {@code null} to find the class in the 737 * {@linkplain #getUnnamedModule() unnamed module} for this 738 * class loader 739 * @param name 740 * The <a href="#binary-name">binary name</a> of the class 741 * 742 * @return The resulting {@code Class} object, or {@code null} 743 * if the class could not be found. 744 * 745 * @since 9 746 * @spec JPMS 747 */ 748 protected Class<?> findClass(String moduleName, String name) { 749 if (moduleName == null) { 750 try { 751 return findClass(name); 752 } catch (ClassNotFoundException ignore) { } 753 } 754 return null; 755 } 756 757 758 /** 759 * Converts an array of bytes into an instance of class {@code Class}. 760 * Before the {@code Class} can be used it must be resolved. This method 761 * is deprecated in favor of the version that takes a <a 762 * href="#binary-name">binary name</a> as its first argument, and is more secure. 763 * 764 * @param b 765 * The bytes that make up the class data. The bytes in positions 766 * {@code off} through {@code off+len-1} should have the format 767 * of a valid class file as defined by 768 * <cite>The Java Virtual Machine Specification</cite>. 769 * 770 * @param off 771 * The start offset in {@code b} of the class data 772 * 773 * @param len 774 * The length of the class data 775 * 776 * @return The {@code Class} object that was created from the specified 777 * class data 778 * 779 * @throws ClassFormatError 780 * If the data did not contain a valid class 781 * 782 * @throws IndexOutOfBoundsException 783 * If either {@code off} or {@code len} is negative, or if 784 * {@code off+len} is greater than {@code b.length}. 785 * 786 * @throws SecurityException 787 * If an attempt is made to add this class to a package that 788 * contains classes that were signed by a different set of 789 * certificates than this class, or if an attempt is made 790 * to define a class in a package with a fully-qualified name 791 * that starts with "{@code java.}". 792 * 793 * @see #loadClass(String, boolean) 794 * @see #resolveClass(Class) 795 * 796 * @deprecated Replaced by {@link #defineClass(String, byte[], int, int) 797 * defineClass(String, byte[], int, int)} 798 */ 799 @Deprecated(since="1.1") 800 protected final Class<?> defineClass(byte[] b, int off, int len) 801 throws ClassFormatError 802 { 803 return defineClass(null, b, off, len, null); 804 } 805 806 /** 807 * Converts an array of bytes into an instance of class {@code Class}. 808 * Before the {@code Class} can be used it must be resolved. 809 * 810 * <p> This method assigns a default {@link java.security.ProtectionDomain 811 * ProtectionDomain} to the newly defined class. The 812 * {@code ProtectionDomain} is effectively granted the same set of 813 * permissions returned when {@link 814 * java.security.Policy#getPermissions(java.security.CodeSource) 815 * Policy.getPolicy().getPermissions(new CodeSource(null, null))} 816 * is invoked. The default protection domain is created on the first invocation 817 * of {@link #defineClass(String, byte[], int, int) defineClass}, 818 * and re-used on subsequent invocations. 819 * 820 * <p> To assign a specific {@code ProtectionDomain} to the class, use 821 * the {@link #defineClass(String, byte[], int, int, 822 * java.security.ProtectionDomain) defineClass} method that takes a 823 * {@code ProtectionDomain} as one of its arguments. </p> 824 * 825 * <p> 826 * This method defines a package in this class loader corresponding to the 827 * package of the {@code Class} (if such a package has not already been defined 828 * in this class loader). The name of the defined package is derived from 829 * the <a href="#binary-name">binary name</a> of the class specified by 830 * the byte array {@code b}. 831 * Other properties of the defined package are as specified by {@link Package}. 832 * 833 * @param name 834 * The expected <a href="#binary-name">binary name</a> of the class, or 835 * {@code null} if not known 836 * 837 * @param b 838 * The bytes that make up the class data. The bytes in positions 839 * {@code off} through {@code off+len-1} should have the format 840 * of a valid class file as defined by 841 * <cite>The Java Virtual Machine Specification</cite>. 842 * 843 * @param off 844 * The start offset in {@code b} of the class data 845 * 846 * @param len 847 * The length of the class data 848 * 849 * @return The {@code Class} object that was created from the specified 850 * class data. 851 * 852 * @throws ClassFormatError 853 * If the data did not contain a valid class 854 * 855 * @throws IndexOutOfBoundsException 856 * If either {@code off} or {@code len} is negative, or if 857 * {@code off+len} is greater than {@code b.length}. 858 * 859 * @throws SecurityException 860 * If an attempt is made to add this class to a package that 861 * contains classes that were signed by a different set of 862 * certificates than this class (which is unsigned), or if 863 * {@code name} begins with "{@code java.}". 864 * 865 * @see #loadClass(String, boolean) 866 * @see #resolveClass(Class) 867 * @see java.security.CodeSource 868 * @see java.security.SecureClassLoader 869 * 870 * @since 1.1 871 * @revised 9 872 * @spec JPMS 873 */ 874 protected final Class<?> defineClass(String name, byte[] b, int off, int len) 875 throws ClassFormatError 876 { 877 return defineClass(name, b, off, len, null); 878 } 879 880 /* Determine protection domain, and check that: 881 - not define java.* class, 882 - signer of this class matches signers for the rest of the classes in 883 package. 884 */ 885 private ProtectionDomain preDefineClass(String name, 886 ProtectionDomain pd) 887 { 888 if (!checkName(name)) 889 throw new NoClassDefFoundError("IllegalName: " + name); 890 891 // Note: Checking logic in java.lang.invoke.MemberName.checkForTypeAlias 892 // relies on the fact that spoofing is impossible if a class has a name 893 // of the form "java.*" 894 if ((name != null) && name.startsWith("java.") 895 && this != getBuiltinPlatformClassLoader()) { 896 throw new SecurityException 897 ("Prohibited package name: " + 898 name.substring(0, name.lastIndexOf('.'))); 899 } 900 if (pd == null) { 901 pd = defaultDomain; 902 } 903 904 if (name != null) { 905 checkCerts(name, pd.getCodeSource()); 906 } 907 908 return pd; 909 } 910 911 private String defineClassSourceLocation(ProtectionDomain pd) { 912 CodeSource cs = pd.getCodeSource(); 913 String source = null; 914 if (cs != null && cs.getLocation() != null) { 915 source = cs.getLocation().toString(); 916 } 917 return source; 918 } 919 920 private void postDefineClass(Class<?> c, ProtectionDomain pd) { 921 // define a named package, if not present 922 getNamedPackage(c.getPackageName(), c.getModule()); 923 924 if (pd.getCodeSource() != null) { 925 Certificate certs[] = pd.getCodeSource().getCertificates(); 926 if (certs != null) 927 setSigners(c, certs); 928 } 929 } 930 931 /** 932 * Converts an array of bytes into an instance of class {@code Class}, 933 * with a given {@code ProtectionDomain}. 934 * 935 * <p> If the given {@code ProtectionDomain} is {@code null}, 936 * then a default protection domain will be assigned to the class as specified 937 * in the documentation for {@link #defineClass(String, byte[], int, int)}. 938 * Before the class can be used it must be resolved. 939 * 940 * <p> The first class defined in a package determines the exact set of 941 * certificates that all subsequent classes defined in that package must 942 * contain. The set of certificates for a class is obtained from the 943 * {@link java.security.CodeSource CodeSource} within the 944 * {@code ProtectionDomain} of the class. Any classes added to that 945 * package must contain the same set of certificates or a 946 * {@code SecurityException} will be thrown. Note that if 947 * {@code name} is {@code null}, this check is not performed. 948 * You should always pass in the <a href="#binary-name">binary name</a> of the 949 * class you are defining as well as the bytes. This ensures that the 950 * class you are defining is indeed the class you think it is. 951 * 952 * <p> If the specified {@code name} begins with "{@code java.}", it can 953 * only be defined by the {@linkplain #getPlatformClassLoader() 954 * platform class loader} or its ancestors; otherwise {@code SecurityException} 955 * will be thrown. If {@code name} is not {@code null}, it must be equal to 956 * the <a href="#binary-name">binary name</a> of the class 957 * specified by the byte array {@code b}, otherwise a {@link 958 * NoClassDefFoundError NoClassDefFoundError} will be thrown. 959 * 960 * <p> This method defines a package in this class loader corresponding to the 961 * package of the {@code Class} (if such a package has not already been defined 962 * in this class loader). The name of the defined package is derived from 963 * the <a href="#binary-name">binary name</a> of the class specified by 964 * the byte array {@code b}. 965 * Other properties of the defined package are as specified by {@link Package}. 966 * 967 * @param name 968 * The expected <a href="#binary-name">binary name</a> of the class, or 969 * {@code null} if not known 970 * 971 * @param b 972 * The bytes that make up the class data. The bytes in positions 973 * {@code off} through {@code off+len-1} should have the format 974 * of a valid class file as defined by 975 * <cite>The Java Virtual Machine Specification</cite>. 976 * 977 * @param off 978 * The start offset in {@code b} of the class data 979 * 980 * @param len 981 * The length of the class data 982 * 983 * @param protectionDomain 984 * The {@code ProtectionDomain} of the class 985 * 986 * @return The {@code Class} object created from the data, 987 * and {@code ProtectionDomain}. 988 * 989 * @throws ClassFormatError 990 * If the data did not contain a valid class 991 * 992 * @throws NoClassDefFoundError 993 * If {@code name} is not {@code null} and not equal to the 994 * <a href="#binary-name">binary name</a> of the class specified by {@code b} 995 * 996 * @throws IndexOutOfBoundsException 997 * If either {@code off} or {@code len} is negative, or if 998 * {@code off+len} is greater than {@code b.length}. 999 * 1000 * @throws SecurityException 1001 * If an attempt is made to add this class to a package that 1002 * contains classes that were signed by a different set of 1003 * certificates than this class, or if {@code name} begins with 1004 * "{@code java.}" and this class loader is not the platform 1005 * class loader or its ancestor. 1006 * 1007 * @revised 9 1008 * @spec JPMS 1009 */ 1010 protected final Class<?> defineClass(String name, byte[] b, int off, int len, 1011 ProtectionDomain protectionDomain) 1012 throws ClassFormatError 1013 { 1014 protectionDomain = preDefineClass(name, protectionDomain); 1015 String source = defineClassSourceLocation(protectionDomain); 1016 Class<?> c = defineClass1(this, name, b, off, len, protectionDomain, source); 1017 postDefineClass(c, protectionDomain); 1018 return c; 1019 } 1020 1021 /** 1022 * Converts a {@link java.nio.ByteBuffer ByteBuffer} into an instance 1023 * of class {@code Class}, with the given {@code ProtectionDomain}. 1024 * If the given {@code ProtectionDomain} is {@code null}, then a default 1025 * protection domain will be assigned to the class as 1026 * specified in the documentation for {@link #defineClass(String, byte[], 1027 * int, int)}. Before the class can be used it must be resolved. 1028 * 1029 * <p>The rules about the first class defined in a package determining the 1030 * set of certificates for the package, the restrictions on class names, 1031 * and the defined package of the class 1032 * are identical to those specified in the documentation for {@link 1033 * #defineClass(String, byte[], int, int, ProtectionDomain)}. 1034 * 1035 * <p> An invocation of this method of the form 1036 * <i>cl</i>{@code .defineClass(}<i>name</i>{@code ,} 1037 * <i>bBuffer</i>{@code ,} <i>pd</i>{@code )} yields exactly the same 1038 * result as the statements 1039 * 1040 *<p> <code> 1041 * ...<br> 1042 * byte[] temp = new byte[bBuffer.{@link 1043 * java.nio.ByteBuffer#remaining remaining}()];<br> 1044 * bBuffer.{@link java.nio.ByteBuffer#get(byte[]) 1045 * get}(temp);<br> 1046 * return {@link #defineClass(String, byte[], int, int, ProtectionDomain) 1047 * cl.defineClass}(name, temp, 0, 1048 * temp.length, pd);<br> 1049 * </code></p> 1050 * 1051 * @param name 1052 * The expected <a href="#binary-name">binary name</a>. of the class, or 1053 * {@code null} if not known 1054 * 1055 * @param b 1056 * The bytes that make up the class data. The bytes from positions 1057 * {@code b.position()} through {@code b.position() + b.limit() -1 1058 * } should have the format of a valid class file as defined by 1059 * <cite>The Java Virtual Machine Specification</cite>. 1060 * 1061 * @param protectionDomain 1062 * The {@code ProtectionDomain} of the class, or {@code null}. 1063 * 1064 * @return The {@code Class} object created from the data, 1065 * and {@code ProtectionDomain}. 1066 * 1067 * @throws ClassFormatError 1068 * If the data did not contain a valid class. 1069 * 1070 * @throws NoClassDefFoundError 1071 * If {@code name} is not {@code null} and not equal to the 1072 * <a href="#binary-name">binary name</a> of the class specified by {@code b} 1073 * 1074 * @throws SecurityException 1075 * If an attempt is made to add this class to a package that 1076 * contains classes that were signed by a different set of 1077 * certificates than this class, or if {@code name} begins with 1078 * "{@code java.}". 1079 * 1080 * @see #defineClass(String, byte[], int, int, ProtectionDomain) 1081 * 1082 * @since 1.5 1083 * @revised 9 1084 * @spec JPMS 1085 */ 1086 protected final Class<?> defineClass(String name, java.nio.ByteBuffer b, 1087 ProtectionDomain protectionDomain) 1088 throws ClassFormatError 1089 { 1090 int len = b.remaining(); 1091 1092 // Use byte[] if not a direct ByteBuffer: 1093 if (!b.isDirect()) { 1094 if (b.hasArray()) { 1095 return defineClass(name, b.array(), 1096 b.position() + b.arrayOffset(), len, 1097 protectionDomain); 1098 } else { 1099 // no array, or read-only array 1100 byte[] tb = new byte[len]; 1101 b.get(tb); // get bytes out of byte buffer. 1102 return defineClass(name, tb, 0, len, protectionDomain); 1103 } 1104 } 1105 1106 protectionDomain = preDefineClass(name, protectionDomain); 1107 String source = defineClassSourceLocation(protectionDomain); 1108 Class<?> c = defineClass2(this, name, b, b.position(), len, protectionDomain, source); 1109 postDefineClass(c, protectionDomain); 1110 return c; 1111 } 1112 1113 static native Class<?> defineClass1(ClassLoader loader, String name, byte[] b, int off, int len, 1114 ProtectionDomain pd, String source); 1115 1116 static native Class<?> defineClass2(ClassLoader loader, String name, java.nio.ByteBuffer b, 1117 int off, int len, ProtectionDomain pd, 1118 String source); 1119 1120 /** 1121 * Defines a class of the given flags via Lookup.defineClass. 1122 * 1123 * @param loader the defining loader 1124 * @param lookup nest host of the Class to be defined 1125 * @param name the binary name or {@code null} if not findable 1126 * @param b class bytes 1127 * @param off the start offset in {@code b} of the class bytes 1128 * @param len the length of the class bytes 1129 * @param pd protection domain 1130 * @param initialize initialize the class 1131 * @param flags flags 1132 * @param classData class data 1133 */ 1134 static native Class<?> defineClass0(ClassLoader loader, 1135 Class<?> lookup, 1136 String name, 1137 byte[] b, int off, int len, 1138 ProtectionDomain pd, 1139 boolean initialize, 1140 int flags, 1141 Object classData); 1142 1143 // true if the name is null or has the potential to be a valid binary name 1144 private boolean checkName(String name) { 1145 if ((name == null) || (name.isEmpty())) 1146 return true; 1147 if ((name.indexOf('/') != -1) || (name.charAt(0) == '[')) 1148 return false; 1149 return true; 1150 } 1151 1152 private void checkCerts(String name, CodeSource cs) { 1153 int i = name.lastIndexOf('.'); 1154 String pname = (i == -1) ? "" : name.substring(0, i); 1155 1156 Certificate[] certs = null; 1157 if (cs != null) { 1158 certs = cs.getCertificates(); 1159 } 1160 certs = certs == null ? nocerts : certs; 1161 Certificate[] pcerts = package2certs.putIfAbsent(pname, certs); 1162 if (pcerts != null && !compareCerts(pcerts, certs)) { 1163 throw new SecurityException("class \"" + name 1164 + "\"'s signer information does not match signer information" 1165 + " of other classes in the same package"); 1166 } 1167 } 1168 1169 /** 1170 * check to make sure the certs for the new class (certs) are the same as 1171 * the certs for the first class inserted in the package (pcerts) 1172 */ 1173 private boolean compareCerts(Certificate[] pcerts, Certificate[] certs) { 1174 // empty array fast-path 1175 if (certs.length == 0) 1176 return pcerts.length == 0; 1177 1178 // the length must be the same at this point 1179 if (certs.length != pcerts.length) 1180 return false; 1181 1182 // go through and make sure all the certs in one array 1183 // are in the other and vice-versa. 1184 boolean match; 1185 for (Certificate cert : certs) { 1186 match = false; 1187 for (Certificate pcert : pcerts) { 1188 if (cert.equals(pcert)) { 1189 match = true; 1190 break; 1191 } 1192 } 1193 if (!match) return false; 1194 } 1195 1196 // now do the same for pcerts 1197 for (Certificate pcert : pcerts) { 1198 match = false; 1199 for (Certificate cert : certs) { 1200 if (pcert.equals(cert)) { 1201 match = true; 1202 break; 1203 } 1204 } 1205 if (!match) return false; 1206 } 1207 1208 return true; 1209 } 1210 1211 /** 1212 * Links the specified class. This (misleadingly named) method may be 1213 * used by a class loader to link a class. If the class {@code c} has 1214 * already been linked, then this method simply returns. Otherwise, the 1215 * class is linked as described in the "Execution" chapter of 1216 * <cite>The Java Language Specification</cite>. 1217 * 1218 * @param c 1219 * The class to link 1220 * 1221 * @throws NullPointerException 1222 * If {@code c} is {@code null}. 1223 * 1224 * @see #defineClass(String, byte[], int, int) 1225 */ 1226 protected final void resolveClass(Class<?> c) { 1227 if (c == null) { 1228 throw new NullPointerException(); 1229 } 1230 } 1231 1232 /** 1233 * Finds a class with the specified <a href="#binary-name">binary name</a>, 1234 * loading it if necessary. 1235 * 1236 * <p> This method loads the class through the system class loader (see 1237 * {@link #getSystemClassLoader()}). The {@code Class} object returned 1238 * might have more than one {@code ClassLoader} associated with it. 1239 * Subclasses of {@code ClassLoader} need not usually invoke this method, 1240 * because most class loaders need to override just {@link 1241 * #findClass(String)}. </p> 1242 * 1243 * @param name 1244 * The <a href="#binary-name">binary name</a> of the class 1245 * 1246 * @return The {@code Class} object for the specified {@code name} 1247 * 1248 * @throws ClassNotFoundException 1249 * If the class could not be found 1250 * 1251 * @see #ClassLoader(ClassLoader) 1252 * @see #getParent() 1253 */ 1254 protected final Class<?> findSystemClass(String name) 1255 throws ClassNotFoundException 1256 { 1257 return getSystemClassLoader().loadClass(name); 1258 } 1259 1260 /** 1261 * Returns a class loaded by the bootstrap class loader; 1262 * or return null if not found. 1263 */ 1264 Class<?> findBootstrapClassOrNull(String name) { 1265 if (!checkName(name)) return null; 1266 1267 return findBootstrapClass(name); 1268 } 1269 1270 // return null if not found 1271 private native Class<?> findBootstrapClass(String name); 1272 1273 /** 1274 * Returns the class with the given <a href="#binary-name">binary name</a> if this 1275 * loader has been recorded by the Java virtual machine as an initiating 1276 * loader of a class with that <a href="#binary-name">binary name</a>. Otherwise 1277 * {@code null} is returned. 1278 * 1279 * @param name 1280 * The <a href="#binary-name">binary name</a> of the class 1281 * 1282 * @return The {@code Class} object, or {@code null} if the class has 1283 * not been loaded 1284 * 1285 * @since 1.1 1286 */ 1287 protected final Class<?> findLoadedClass(String name) { 1288 if (!checkName(name)) 1289 return null; 1290 return findLoadedClass0(name); 1291 } 1292 1293 private final native Class<?> findLoadedClass0(String name); 1294 1295 /** 1296 * Sets the signers of a class. This should be invoked after defining a 1297 * class. 1298 * 1299 * @param c 1300 * The {@code Class} object 1301 * 1302 * @param signers 1303 * The signers for the class 1304 * 1305 * @since 1.1 1306 */ 1307 protected final void setSigners(Class<?> c, Object[] signers) { 1308 c.setSigners(signers); 1309 } 1310 1311 1312 // -- Resources -- 1313 1314 /** 1315 * Returns a URL to a resource in a module defined to this class loader. 1316 * Class loader implementations that support loading from modules 1317 * should override this method. 1318 * 1319 * @apiNote This method is the basis for the {@link 1320 * Class#getResource Class.getResource}, {@link Class#getResourceAsStream 1321 * Class.getResourceAsStream}, and {@link Module#getResourceAsStream 1322 * Module.getResourceAsStream} methods. It is not subject to the rules for 1323 * encapsulation specified by {@code Module.getResourceAsStream}. 1324 * 1325 * @implSpec The default implementation attempts to find the resource by 1326 * invoking {@link #findResource(String)} when the {@code moduleName} is 1327 * {@code null}. It otherwise returns {@code null}. 1328 * 1329 * @param moduleName 1330 * The module name; or {@code null} to find a resource in the 1331 * {@linkplain #getUnnamedModule() unnamed module} for this 1332 * class loader 1333 * @param name 1334 * The resource name 1335 * 1336 * @return A URL to the resource; {@code null} if the resource could not be 1337 * found, a URL could not be constructed to locate the resource, 1338 * access to the resource is denied by the security manager, or 1339 * there isn't a module of the given name defined to the class 1340 * loader. 1341 * 1342 * @throws IOException 1343 * If I/O errors occur 1344 * 1345 * @see java.lang.module.ModuleReader#find(String) 1346 * @since 9 1347 * @spec JPMS 1348 */ 1349 protected URL findResource(String moduleName, String name) throws IOException { 1350 if (moduleName == null) { 1351 return findResource(name); 1352 } else { 1353 return null; 1354 } 1355 } 1356 1357 /** 1358 * Finds the resource with the given name. A resource is some data 1359 * (images, audio, text, etc) that can be accessed by class code in a way 1360 * that is independent of the location of the code. 1361 * 1362 * <p> The name of a resource is a '{@code /}'-separated path name that 1363 * identifies the resource. </p> 1364 * 1365 * <p> Resources in named modules are subject to the encapsulation rules 1366 * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}. 1367 * Additionally, and except for the special case where the resource has a 1368 * name ending with "{@code .class}", this method will only find resources in 1369 * packages of named modules when the package is {@link Module#isOpen(String) 1370 * opened} unconditionally (even if the caller of this method is in the 1371 * same module as the resource). </p> 1372 * 1373 * @implSpec The default implementation will first search the parent class 1374 * loader for the resource; if the parent is {@code null} the path of the 1375 * class loader built into the virtual machine is searched. If not found, 1376 * this method will invoke {@link #findResource(String)} to find the resource. 1377 * 1378 * @apiNote Where several modules are defined to the same class loader, 1379 * and where more than one module contains a resource with the given name, 1380 * then the ordering that modules are searched is not specified and may be 1381 * very unpredictable. 1382 * When overriding this method it is recommended that an implementation 1383 * ensures that any delegation is consistent with the {@link 1384 * #getResources(java.lang.String) getResources(String)} method. 1385 * 1386 * @param name 1387 * The resource name 1388 * 1389 * @return {@code URL} object for reading the resource; {@code null} if 1390 * the resource could not be found, a {@code URL} could not be 1391 * constructed to locate the resource, the resource is in a package 1392 * that is not opened unconditionally, or access to the resource is 1393 * denied by the security manager. 1394 * 1395 * @throws NullPointerException If {@code name} is {@code null} 1396 * 1397 * @since 1.1 1398 * @revised 9 1399 * @spec JPMS 1400 */ 1401 public URL getResource(String name) { 1402 Objects.requireNonNull(name); 1403 URL url; 1404 if (parent != null) { 1405 url = parent.getResource(name); 1406 } else { 1407 url = BootLoader.findResource(name); 1408 } 1409 if (url == null) { 1410 url = findResource(name); 1411 } 1412 return url; 1413 } 1414 1415 /** 1416 * Finds all the resources with the given name. A resource is some data 1417 * (images, audio, text, etc) that can be accessed by class code in a way 1418 * that is independent of the location of the code. 1419 * 1420 * <p> The name of a resource is a {@code /}-separated path name that 1421 * identifies the resource. </p> 1422 * 1423 * <p> Resources in named modules are subject to the encapsulation rules 1424 * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}. 1425 * Additionally, and except for the special case where the resource has a 1426 * name ending with "{@code .class}", this method will only find resources in 1427 * packages of named modules when the package is {@link Module#isOpen(String) 1428 * opened} unconditionally (even if the caller of this method is in the 1429 * same module as the resource). </p> 1430 * 1431 * @implSpec The default implementation will first search the parent class 1432 * loader for the resource; if the parent is {@code null} the path of the 1433 * class loader built into the virtual machine is searched. It then 1434 * invokes {@link #findResources(String)} to find the resources with the 1435 * name in this class loader. It returns an enumeration whose elements 1436 * are the URLs found by searching the parent class loader followed by 1437 * the elements found with {@code findResources}. 1438 * 1439 * @apiNote Where several modules are defined to the same class loader, 1440 * and where more than one module contains a resource with the given name, 1441 * then the ordering is not specified and may be very unpredictable. 1442 * When overriding this method it is recommended that an 1443 * implementation ensures that any delegation is consistent with the {@link 1444 * #getResource(java.lang.String) getResource(String)} method. This should 1445 * ensure that the first element returned by the Enumeration's 1446 * {@code nextElement} method is the same resource that the 1447 * {@code getResource(String)} method would return. 1448 * 1449 * @param name 1450 * The resource name 1451 * 1452 * @return An enumeration of {@link java.net.URL URL} objects for the 1453 * resource. If no resources could be found, the enumeration will 1454 * be empty. Resources for which a {@code URL} cannot be 1455 * constructed, are in a package that is not opened 1456 * unconditionally, or access to the resource is denied by the 1457 * security manager, are not returned in the enumeration. 1458 * 1459 * @throws IOException 1460 * If I/O errors occur 1461 * @throws NullPointerException If {@code name} is {@code null} 1462 * 1463 * @since 1.2 1464 * @revised 9 1465 * @spec JPMS 1466 */ 1467 public Enumeration<URL> getResources(String name) throws IOException { 1468 Objects.requireNonNull(name); 1469 @SuppressWarnings("unchecked") 1470 Enumeration<URL>[] tmp = (Enumeration<URL>[]) new Enumeration<?>[2]; 1471 if (parent != null) { 1472 tmp[0] = parent.getResources(name); 1473 } else { 1474 tmp[0] = BootLoader.findResources(name); 1475 } 1476 tmp[1] = findResources(name); 1477 1478 return new CompoundEnumeration<>(tmp); 1479 } 1480 1481 /** 1482 * Returns a stream whose elements are the URLs of all the resources with 1483 * the given name. A resource is some data (images, audio, text, etc) that 1484 * can be accessed by class code in a way that is independent of the 1485 * location of the code. 1486 * 1487 * <p> The name of a resource is a {@code /}-separated path name that 1488 * identifies the resource. 1489 * 1490 * <p> The resources will be located when the returned stream is evaluated. 1491 * If the evaluation results in an {@code IOException} then the I/O 1492 * exception is wrapped in an {@link UncheckedIOException} that is then 1493 * thrown. 1494 * 1495 * <p> Resources in named modules are subject to the encapsulation rules 1496 * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}. 1497 * Additionally, and except for the special case where the resource has a 1498 * name ending with "{@code .class}", this method will only find resources in 1499 * packages of named modules when the package is {@link Module#isOpen(String) 1500 * opened} unconditionally (even if the caller of this method is in the 1501 * same module as the resource). </p> 1502 * 1503 * @implSpec The default implementation invokes {@link #getResources(String) 1504 * getResources} to find all the resources with the given name and returns 1505 * a stream with the elements in the enumeration as the source. 1506 * 1507 * @apiNote When overriding this method it is recommended that an 1508 * implementation ensures that any delegation is consistent with the {@link 1509 * #getResource(java.lang.String) getResource(String)} method. This should 1510 * ensure that the first element returned by the stream is the same 1511 * resource that the {@code getResource(String)} method would return. 1512 * 1513 * @param name 1514 * The resource name 1515 * 1516 * @return A stream of resource {@link java.net.URL URL} objects. If no 1517 * resources could be found, the stream will be empty. Resources 1518 * for which a {@code URL} cannot be constructed, are in a package 1519 * that is not opened unconditionally, or access to the resource 1520 * is denied by the security manager, will not be in the stream. 1521 * 1522 * @throws NullPointerException If {@code name} is {@code null} 1523 * 1524 * @since 9 1525 */ 1526 public Stream<URL> resources(String name) { 1527 Objects.requireNonNull(name); 1528 int characteristics = Spliterator.NONNULL | Spliterator.IMMUTABLE; 1529 Supplier<Spliterator<URL>> si = () -> { 1530 try { 1531 return Spliterators.spliteratorUnknownSize( 1532 getResources(name).asIterator(), characteristics); 1533 } catch (IOException e) { 1534 throw new UncheckedIOException(e); 1535 } 1536 }; 1537 return StreamSupport.stream(si, characteristics, false); 1538 } 1539 1540 /** 1541 * Finds the resource with the given name. Class loader implementations 1542 * should override this method. 1543 * 1544 * <p> For resources in named modules then the method must implement the 1545 * rules for encapsulation specified in the {@code Module} {@link 1546 * Module#getResourceAsStream getResourceAsStream} method. Additionally, 1547 * it must not find non-"{@code .class}" resources in packages of named 1548 * modules unless the package is {@link Module#isOpen(String) opened} 1549 * unconditionally. </p> 1550 * 1551 * @implSpec The default implementation returns {@code null}. 1552 * 1553 * @param name 1554 * The resource name 1555 * 1556 * @return {@code URL} object for reading the resource; {@code null} if 1557 * the resource could not be found, a {@code URL} could not be 1558 * constructed to locate the resource, the resource is in a package 1559 * that is not opened unconditionally, or access to the resource is 1560 * denied by the security manager. 1561 * 1562 * @since 1.2 1563 * @revised 9 1564 * @spec JPMS 1565 */ 1566 protected URL findResource(String name) { 1567 return null; 1568 } 1569 1570 /** 1571 * Returns an enumeration of {@link java.net.URL URL} objects 1572 * representing all the resources with the given name. Class loader 1573 * implementations should override this method. 1574 * 1575 * <p> For resources in named modules then the method must implement the 1576 * rules for encapsulation specified in the {@code Module} {@link 1577 * Module#getResourceAsStream getResourceAsStream} method. Additionally, 1578 * it must not find non-"{@code .class}" resources in packages of named 1579 * modules unless the package is {@link Module#isOpen(String) opened} 1580 * unconditionally. </p> 1581 * 1582 * @implSpec The default implementation returns an enumeration that 1583 * contains no elements. 1584 * 1585 * @param name 1586 * The resource name 1587 * 1588 * @return An enumeration of {@link java.net.URL URL} objects for 1589 * the resource. If no resources could be found, the enumeration 1590 * will be empty. Resources for which a {@code URL} cannot be 1591 * constructed, are in a package that is not opened unconditionally, 1592 * or access to the resource is denied by the security manager, 1593 * are not returned in the enumeration. 1594 * 1595 * @throws IOException 1596 * If I/O errors occur 1597 * 1598 * @since 1.2 1599 * @revised 9 1600 * @spec JPMS 1601 */ 1602 protected Enumeration<URL> findResources(String name) throws IOException { 1603 return Collections.emptyEnumeration(); 1604 } 1605 1606 /** 1607 * Registers the caller as 1608 * {@linkplain #isRegisteredAsParallelCapable() parallel capable}. 1609 * The registration succeeds if and only if all of the following 1610 * conditions are met: 1611 * <ol> 1612 * <li> no instance of the caller has been created</li> 1613 * <li> all of the super classes (except class Object) of the caller are 1614 * registered as parallel capable</li> 1615 * </ol> 1616 * <p>Note that once a class loader is registered as parallel capable, there 1617 * is no way to change it back.</p> 1618 * 1619 * @return {@code true} if the caller is successfully registered as 1620 * parallel capable and {@code false} if otherwise. 1621 * 1622 * @see #isRegisteredAsParallelCapable() 1623 * 1624 * @since 1.7 1625 */ 1626 @CallerSensitive 1627 protected static boolean registerAsParallelCapable() { 1628 Class<? extends ClassLoader> callerClass = 1629 Reflection.getCallerClass().asSubclass(ClassLoader.class); 1630 return ParallelLoaders.register(callerClass); 1631 } 1632 1633 /** 1634 * Returns {@code true} if this class loader is registered as 1635 * {@linkplain #registerAsParallelCapable parallel capable}, otherwise 1636 * {@code false}. 1637 * 1638 * @return {@code true} if this class loader is parallel capable, 1639 * otherwise {@code false}. 1640 * 1641 * @see #registerAsParallelCapable() 1642 * 1643 * @since 9 1644 */ 1645 public final boolean isRegisteredAsParallelCapable() { 1646 return ParallelLoaders.isRegistered(this.getClass()); 1647 } 1648 1649 /** 1650 * Find a resource of the specified name from the search path used to load 1651 * classes. This method locates the resource through the system class 1652 * loader (see {@link #getSystemClassLoader()}). 1653 * 1654 * <p> Resources in named modules are subject to the encapsulation rules 1655 * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}. 1656 * Additionally, and except for the special case where the resource has a 1657 * name ending with "{@code .class}", this method will only find resources in 1658 * packages of named modules when the package is {@link Module#isOpen(String) 1659 * opened} unconditionally. </p> 1660 * 1661 * @param name 1662 * The resource name 1663 * 1664 * @return A {@link java.net.URL URL} to the resource; {@code 1665 * null} if the resource could not be found, a URL could not be 1666 * constructed to locate the resource, the resource is in a package 1667 * that is not opened unconditionally or access to the resource is 1668 * denied by the security manager. 1669 * 1670 * @since 1.1 1671 * @revised 9 1672 * @spec JPMS 1673 */ 1674 public static URL getSystemResource(String name) { 1675 return getSystemClassLoader().getResource(name); 1676 } 1677 1678 /** 1679 * Finds all resources of the specified name from the search path used to 1680 * load classes. The resources thus found are returned as an 1681 * {@link java.util.Enumeration Enumeration} of {@link 1682 * java.net.URL URL} objects. 1683 * 1684 * <p> The search order is described in the documentation for {@link 1685 * #getSystemResource(String)}. </p> 1686 * 1687 * <p> Resources in named modules are subject to the encapsulation rules 1688 * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}. 1689 * Additionally, and except for the special case where the resource has a 1690 * name ending with "{@code .class}", this method will only find resources in 1691 * packages of named modules when the package is {@link Module#isOpen(String) 1692 * opened} unconditionally. </p> 1693 * 1694 * @param name 1695 * The resource name 1696 * 1697 * @return An enumeration of {@link java.net.URL URL} objects for 1698 * the resource. If no resources could be found, the enumeration 1699 * will be empty. Resources for which a {@code URL} cannot be 1700 * constructed, are in a package that is not opened unconditionally, 1701 * or access to the resource is denied by the security manager, 1702 * are not returned in the enumeration. 1703 * 1704 * @throws IOException 1705 * If I/O errors occur 1706 * 1707 * @since 1.2 1708 * @revised 9 1709 * @spec JPMS 1710 */ 1711 public static Enumeration<URL> getSystemResources(String name) 1712 throws IOException 1713 { 1714 return getSystemClassLoader().getResources(name); 1715 } 1716 1717 /** 1718 * Returns an input stream for reading the specified resource. 1719 * 1720 * <p> The search order is described in the documentation for {@link 1721 * #getResource(String)}. </p> 1722 * 1723 * <p> Resources in named modules are subject to the encapsulation rules 1724 * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}. 1725 * Additionally, and except for the special case where the resource has a 1726 * name ending with "{@code .class}", this method will only find resources in 1727 * packages of named modules when the package is {@link Module#isOpen(String) 1728 * opened} unconditionally. </p> 1729 * 1730 * @param name 1731 * The resource name 1732 * 1733 * @return An input stream for reading the resource; {@code null} if the 1734 * resource could not be found, the resource is in a package that 1735 * is not opened unconditionally, or access to the resource is 1736 * denied by the security manager. 1737 * 1738 * @throws NullPointerException If {@code name} is {@code null} 1739 * 1740 * @since 1.1 1741 * @revised 9 1742 * @spec JPMS 1743 */ 1744 public InputStream getResourceAsStream(String name) { 1745 Objects.requireNonNull(name); 1746 URL url = getResource(name); 1747 try { 1748 return url != null ? url.openStream() : null; 1749 } catch (IOException e) { 1750 return null; 1751 } 1752 } 1753 1754 /** 1755 * Open for reading, a resource of the specified name from the search path 1756 * used to load classes. This method locates the resource through the 1757 * system class loader (see {@link #getSystemClassLoader()}). 1758 * 1759 * <p> Resources in named modules are subject to the encapsulation rules 1760 * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}. 1761 * Additionally, and except for the special case where the resource has a 1762 * name ending with "{@code .class}", this method will only find resources in 1763 * packages of named modules when the package is {@link Module#isOpen(String) 1764 * opened} unconditionally. </p> 1765 * 1766 * @param name 1767 * The resource name 1768 * 1769 * @return An input stream for reading the resource; {@code null} if the 1770 * resource could not be found, the resource is in a package that 1771 * is not opened unconditionally, or access to the resource is 1772 * denied by the security manager. 1773 * 1774 * @since 1.1 1775 * @revised 9 1776 * @spec JPMS 1777 */ 1778 public static InputStream getSystemResourceAsStream(String name) { 1779 URL url = getSystemResource(name); 1780 try { 1781 return url != null ? url.openStream() : null; 1782 } catch (IOException e) { 1783 return null; 1784 } 1785 } 1786 1787 1788 // -- Hierarchy -- 1789 1790 /** 1791 * Returns the parent class loader for delegation. Some implementations may 1792 * use {@code null} to represent the bootstrap class loader. This method 1793 * will return {@code null} in such implementations if this class loader's 1794 * parent is the bootstrap class loader. 1795 * 1796 * @return The parent {@code ClassLoader} 1797 * 1798 * @throws SecurityException 1799 * If a security manager is present, and the caller's class loader 1800 * is not {@code null} and is not an ancestor of this class loader, 1801 * and the caller does not have the 1802 * {@link RuntimePermission}{@code ("getClassLoader")} 1803 * 1804 * @since 1.2 1805 */ 1806 @CallerSensitive 1807 public final ClassLoader getParent() { 1808 if (parent == null) 1809 return null; 1810 SecurityManager sm = System.getSecurityManager(); 1811 if (sm != null) { 1812 // Check access to the parent class loader 1813 // If the caller's class loader is same as this class loader, 1814 // permission check is performed. 1815 checkClassLoaderPermission(parent, Reflection.getCallerClass()); 1816 } 1817 return parent; 1818 } 1819 1820 /** 1821 * Returns the unnamed {@code Module} for this class loader. 1822 * 1823 * @return The unnamed Module for this class loader 1824 * 1825 * @see Module#isNamed() 1826 * @since 9 1827 * @spec JPMS 1828 */ 1829 public final Module getUnnamedModule() { 1830 return unnamedModule; 1831 } 1832 1833 /** 1834 * Returns the platform class loader. All 1835 * <a href="#builtinLoaders">platform classes</a> are visible to 1836 * the platform class loader. 1837 * 1838 * @implNote The name of the builtin platform class loader is 1839 * {@code "platform"}. 1840 * 1841 * @return The platform {@code ClassLoader}. 1842 * 1843 * @throws SecurityException 1844 * If a security manager is present, and the caller's class loader is 1845 * not {@code null}, and the caller's class loader is not the same 1846 * as or an ancestor of the platform class loader, 1847 * and the caller does not have the 1848 * {@link RuntimePermission}{@code ("getClassLoader")} 1849 * 1850 * @since 9 1851 * @spec JPMS 1852 */ 1853 @CallerSensitive 1854 public static ClassLoader getPlatformClassLoader() { 1855 SecurityManager sm = System.getSecurityManager(); 1856 ClassLoader loader = getBuiltinPlatformClassLoader(); 1857 if (sm != null) { 1858 checkClassLoaderPermission(loader, Reflection.getCallerClass()); 1859 } 1860 return loader; 1861 } 1862 1863 /** 1864 * Returns the system class loader. This is the default 1865 * delegation parent for new {@code ClassLoader} instances, and is 1866 * typically the class loader used to start the application. 1867 * 1868 * <p> This method is first invoked early in the runtime's startup 1869 * sequence, at which point it creates the system class loader. This 1870 * class loader will be the context class loader for the main application 1871 * thread (for example, the thread that invokes the {@code main} method of 1872 * the main class). 1873 * 1874 * <p> The default system class loader is an implementation-dependent 1875 * instance of this class. 1876 * 1877 * <p> If the system property "{@systemProperty java.system.class.loader}" 1878 * is defined when this method is first invoked then the value of that 1879 * property is taken to be the name of a class that will be returned as the 1880 * system class loader. The class is loaded using the default system class 1881 * loader and must define a public constructor that takes a single parameter 1882 * of type {@code ClassLoader} which is used as the delegation parent. An 1883 * instance is then created using this constructor with the default system 1884 * class loader as the parameter. The resulting class loader is defined 1885 * to be the system class loader. During construction, the class loader 1886 * should take great care to avoid calling {@code getSystemClassLoader()}. 1887 * If circular initialization of the system class loader is detected then 1888 * an {@code IllegalStateException} is thrown. 1889 * 1890 * @implNote The system property to override the system class loader is not 1891 * examined until the VM is almost fully initialized. Code that executes 1892 * this method during startup should take care not to cache the return 1893 * value until the system is fully initialized. 1894 * 1895 * <p> The name of the built-in system class loader is {@code "app"}. 1896 * The system property "{@code java.class.path}" is read during early 1897 * initialization of the VM to determine the class path. 1898 * An empty value of "{@code java.class.path}" property is interpreted 1899 * differently depending on whether the initial module (the module 1900 * containing the main class) is named or unnamed: 1901 * If named, the built-in system class loader will have no class path and 1902 * will search for classes and resources using the application module path; 1903 * otherwise, if unnamed, it will set the class path to the current 1904 * working directory. 1905 * 1906 * <p> JAR files on the class path may contain a {@code Class-Path} manifest 1907 * attribute to specify dependent JAR files to be included in the class path. 1908 * {@code Class-Path} entries must meet certain conditions for validity (see 1909 * the <a href="{@docRoot}/../specs/jar/jar.html#class-path-attribute"> 1910 * JAR File Specification</a> for details). Invalid {@code Class-Path} 1911 * entries are ignored. For debugging purposes, ignored entries can be 1912 * printed to the console if the 1913 * {@systemProperty jdk.net.URLClassPath.showIgnoredClassPathEntries} system 1914 * property is set to {@code true}. 1915 * 1916 * @return The system {@code ClassLoader} 1917 * 1918 * @throws SecurityException 1919 * If a security manager is present, and the caller's class loader 1920 * is not {@code null} and is not the same as or an ancestor of the 1921 * system class loader, and the caller does not have the 1922 * {@link RuntimePermission}{@code ("getClassLoader")} 1923 * 1924 * @throws IllegalStateException 1925 * If invoked recursively during the construction of the class 1926 * loader specified by the "{@code java.system.class.loader}" 1927 * property. 1928 * 1929 * @throws Error 1930 * If the system property "{@code java.system.class.loader}" 1931 * is defined but the named class could not be loaded, the 1932 * provider class does not define the required constructor, or an 1933 * exception is thrown by that constructor when it is invoked. The 1934 * underlying cause of the error can be retrieved via the 1935 * {@link Throwable#getCause()} method. 1936 * 1937 * @revised 1.4 1938 * @revised 9 1939 * @spec JPMS 1940 */ 1941 @CallerSensitive 1942 public static ClassLoader getSystemClassLoader() { 1943 switch (VM.initLevel()) { 1944 case 0: 1945 case 1: 1946 case 2: 1947 // the system class loader is the built-in app class loader during startup 1948 return getBuiltinAppClassLoader(); 1949 case 3: 1950 String msg = "getSystemClassLoader cannot be called during the system class loader instantiation"; 1951 throw new IllegalStateException(msg); 1952 default: 1953 // system fully initialized 1954 assert VM.isBooted() && scl != null; 1955 SecurityManager sm = System.getSecurityManager(); 1956 if (sm != null) { 1957 checkClassLoaderPermission(scl, Reflection.getCallerClass()); 1958 } 1959 return scl; 1960 } 1961 } 1962 1963 static ClassLoader getBuiltinPlatformClassLoader() { 1964 return ClassLoaders.platformClassLoader(); 1965 } 1966 1967 static ClassLoader getBuiltinAppClassLoader() { 1968 return ClassLoaders.appClassLoader(); 1969 } 1970 1971 /* 1972 * Initialize the system class loader that may be a custom class on the 1973 * application class path or application module path. 1974 * 1975 * @see java.lang.System#initPhase3 1976 */ 1977 static synchronized ClassLoader initSystemClassLoader() { 1978 if (VM.initLevel() != 3) { 1979 throw new InternalError("system class loader cannot be set at initLevel " + 1980 VM.initLevel()); 1981 } 1982 1983 // detect recursive initialization 1984 if (scl != null) { 1985 throw new IllegalStateException("recursive invocation"); 1986 } 1987 1988 ClassLoader builtinLoader = getBuiltinAppClassLoader(); 1989 1990 // All are privileged frames. No need to call doPrivileged. 1991 String cn = System.getProperty("java.system.class.loader"); 1992 if (cn != null) { 1993 try { 1994 // custom class loader is only supported to be loaded from unnamed module 1995 Constructor<?> ctor = Class.forName(cn, false, builtinLoader) 1996 .getDeclaredConstructor(ClassLoader.class); 1997 scl = (ClassLoader) ctor.newInstance(builtinLoader); 1998 } catch (Exception e) { 1999 Throwable cause = e; 2000 if (e instanceof InvocationTargetException) { 2001 cause = e.getCause(); 2002 if (cause instanceof Error) { 2003 throw (Error) cause; 2004 } 2005 } 2006 if (cause instanceof RuntimeException) { 2007 throw (RuntimeException) cause; 2008 } 2009 throw new Error(cause.getMessage(), cause); 2010 } 2011 } else { 2012 scl = builtinLoader; 2013 } 2014 return scl; 2015 } 2016 2017 // Returns true if the specified class loader can be found in this class 2018 // loader's delegation chain. 2019 boolean isAncestor(ClassLoader cl) { 2020 ClassLoader acl = this; 2021 do { 2022 acl = acl.parent; 2023 if (cl == acl) { 2024 return true; 2025 } 2026 } while (acl != null); 2027 return false; 2028 } 2029 2030 // Tests if class loader access requires "getClassLoader" permission 2031 // check. A class loader 'from' can access class loader 'to' if 2032 // class loader 'from' is same as class loader 'to' or an ancestor 2033 // of 'to'. The class loader in a system domain can access 2034 // any class loader. 2035 private static boolean needsClassLoaderPermissionCheck(ClassLoader from, 2036 ClassLoader to) 2037 { 2038 if (from == to) 2039 return false; 2040 2041 if (from == null) 2042 return false; 2043 2044 return !to.isAncestor(from); 2045 } 2046 2047 // Returns the class's class loader, or null if none. 2048 static ClassLoader getClassLoader(Class<?> caller) { 2049 // This can be null if the VM is requesting it 2050 if (caller == null) { 2051 return null; 2052 } 2053 // Circumvent security check since this is package-private 2054 return caller.getClassLoader0(); 2055 } 2056 2057 /* 2058 * Checks RuntimePermission("getClassLoader") permission 2059 * if caller's class loader is not null and caller's class loader 2060 * is not the same as or an ancestor of the given cl argument. 2061 */ 2062 static void checkClassLoaderPermission(ClassLoader cl, Class<?> caller) { 2063 SecurityManager sm = System.getSecurityManager(); 2064 if (sm != null) { 2065 // caller can be null if the VM is requesting it 2066 ClassLoader ccl = getClassLoader(caller); 2067 if (needsClassLoaderPermissionCheck(ccl, cl)) { 2068 sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION); 2069 } 2070 } 2071 } 2072 2073 // The system class loader 2074 // @GuardedBy("ClassLoader.class") 2075 private static volatile ClassLoader scl; 2076 2077 // -- Package -- 2078 2079 /** 2080 * Define a Package of the given Class object. 2081 * 2082 * If the given class represents an array type, a primitive type or void, 2083 * this method returns {@code null}. 2084 * 2085 * This method does not throw IllegalArgumentException. 2086 */ 2087 Package definePackage(Class<?> c) { 2088 if (c.isPrimitive() || c.isArray()) { 2089 return null; 2090 } 2091 2092 return definePackage(c.getPackageName(), c.getModule()); 2093 } 2094 2095 /** 2096 * Defines a Package of the given name and module 2097 * 2098 * This method does not throw IllegalArgumentException. 2099 * 2100 * @param name package name 2101 * @param m module 2102 */ 2103 Package definePackage(String name, Module m) { 2104 if (name.isEmpty() && m.isNamed()) { 2105 throw new InternalError("unnamed package in " + m); 2106 } 2107 2108 // check if Package object is already defined 2109 NamedPackage pkg = packages.get(name); 2110 if (pkg instanceof Package) 2111 return (Package)pkg; 2112 2113 return (Package)packages.compute(name, (n, p) -> toPackage(n, p, m)); 2114 } 2115 2116 /* 2117 * Returns a Package object for the named package 2118 */ 2119 private Package toPackage(String name, NamedPackage p, Module m) { 2120 // define Package object if the named package is not yet defined 2121 if (p == null) 2122 return NamedPackage.toPackage(name, m); 2123 2124 // otherwise, replace the NamedPackage object with Package object 2125 if (p instanceof Package) 2126 return (Package)p; 2127 2128 return NamedPackage.toPackage(p.packageName(), p.module()); 2129 } 2130 2131 /** 2132 * Defines a package by <a href="#binary-name">name</a> in this {@code ClassLoader}. 2133 * <p> 2134 * <a href="#binary-name">Package names</a> must be unique within a class loader and 2135 * cannot be redefined or changed once created. 2136 * <p> 2137 * If a class loader wishes to define a package with specific properties, 2138 * such as version information, then the class loader should call this 2139 * {@code definePackage} method before calling {@code defineClass}. 2140 * Otherwise, the 2141 * {@link #defineClass(String, byte[], int, int, ProtectionDomain) defineClass} 2142 * method will define a package in this class loader corresponding to the package 2143 * of the newly defined class; the properties of this defined package are 2144 * specified by {@link Package}. 2145 * 2146 * @apiNote 2147 * A class loader that wishes to define a package for classes in a JAR 2148 * typically uses the specification and implementation titles, versions, and 2149 * vendors from the JAR's manifest. If the package is specified as 2150 * {@linkplain java.util.jar.Attributes.Name#SEALED sealed} in the JAR's manifest, 2151 * the {@code URL} of the JAR file is typically used as the {@code sealBase}. 2152 * If classes of package {@code 'p'} defined by this class loader 2153 * are loaded from multiple JARs, the {@code Package} object may contain 2154 * different information depending on the first class of package {@code 'p'} 2155 * defined and which JAR's manifest is read first to explicitly define 2156 * package {@code 'p'}. 2157 * 2158 * <p> It is strongly recommended that a class loader does not call this 2159 * method to explicitly define packages in <em>named modules</em>; instead, 2160 * the package will be automatically defined when a class is {@linkplain 2161 * #defineClass(String, byte[], int, int, ProtectionDomain) being defined}. 2162 * If it is desirable to define {@code Package} explicitly, it should ensure 2163 * that all packages in a named module are defined with the properties 2164 * specified by {@link Package}. Otherwise, some {@code Package} objects 2165 * in a named module may be for example sealed with different seal base. 2166 * 2167 * @param name 2168 * The <a href="#binary-name">package name</a> 2169 * 2170 * @param specTitle 2171 * The specification title 2172 * 2173 * @param specVersion 2174 * The specification version 2175 * 2176 * @param specVendor 2177 * The specification vendor 2178 * 2179 * @param implTitle 2180 * The implementation title 2181 * 2182 * @param implVersion 2183 * The implementation version 2184 * 2185 * @param implVendor 2186 * The implementation vendor 2187 * 2188 * @param sealBase 2189 * If not {@code null}, then this package is sealed with 2190 * respect to the given code source {@link java.net.URL URL} 2191 * object. Otherwise, the package is not sealed. 2192 * 2193 * @return The newly defined {@code Package} object 2194 * 2195 * @throws NullPointerException 2196 * if {@code name} is {@code null}. 2197 * 2198 * @throws IllegalArgumentException 2199 * if a package of the given {@code name} is already 2200 * defined by this class loader 2201 * 2202 * 2203 * @since 1.2 2204 * @revised 9 2205 * @spec JPMS 2206 * 2207 * @jvms 5.3 Creation and Loading 2208 * @see <a href="{@docRoot}/../specs/jar/jar.html#package-sealing"> 2209 * The JAR File Specification: Package Sealing</a> 2210 */ 2211 protected Package definePackage(String name, String specTitle, 2212 String specVersion, String specVendor, 2213 String implTitle, String implVersion, 2214 String implVendor, URL sealBase) 2215 { 2216 Objects.requireNonNull(name); 2217 2218 // definePackage is not final and may be overridden by custom class loader 2219 Package p = new Package(name, specTitle, specVersion, specVendor, 2220 implTitle, implVersion, implVendor, 2221 sealBase, this); 2222 2223 if (packages.putIfAbsent(name, p) != null) 2224 throw new IllegalArgumentException(name); 2225 2226 return p; 2227 } 2228 2229 /** 2230 * Returns a {@code Package} of the given <a href="#binary-name">name</a> that 2231 * has been defined by this class loader. 2232 * 2233 * @param name The <a href="#binary-name">package name</a> 2234 * 2235 * @return The {@code Package} of the given name that has been defined 2236 * by this class loader, or {@code null} if not found 2237 * 2238 * @throws NullPointerException 2239 * if {@code name} is {@code null}. 2240 * 2241 * @jvms 5.3 Creation and Loading 2242 * 2243 * @since 9 2244 * @spec JPMS 2245 */ 2246 public final Package getDefinedPackage(String name) { 2247 Objects.requireNonNull(name, "name cannot be null"); 2248 2249 NamedPackage p = packages.get(name); 2250 if (p == null) 2251 return null; 2252 2253 return definePackage(name, p.module()); 2254 } 2255 2256 /** 2257 * Returns all of the {@code Package}s that have been defined by 2258 * this class loader. The returned array has no duplicated {@code Package}s 2259 * of the same name. 2260 * 2261 * @apiNote This method returns an array rather than a {@code Set} or {@code Stream} 2262 * for consistency with the existing {@link #getPackages} method. 2263 * 2264 * @return The array of {@code Package} objects that have been defined by 2265 * this class loader; or an zero length array if no package has been 2266 * defined by this class loader. 2267 * 2268 * @jvms 5.3 Creation and Loading 2269 * 2270 * @since 9 2271 * @spec JPMS 2272 */ 2273 public final Package[] getDefinedPackages() { 2274 return packages().toArray(Package[]::new); 2275 } 2276 2277 /** 2278 * Finds a package by <a href="#binary-name">name</a> in this class loader and its ancestors. 2279 * <p> 2280 * If this class loader defines a {@code Package} of the given name, 2281 * the {@code Package} is returned. Otherwise, the ancestors of 2282 * this class loader are searched recursively (parent by parent) 2283 * for a {@code Package} of the given name. 2284 * 2285 * @apiNote The {@link #getPlatformClassLoader() platform class loader} 2286 * may delegate to the application class loader but the application class 2287 * loader is not its ancestor. When invoked on the platform class loader, 2288 * this method will not find packages defined to the application 2289 * class loader. 2290 * 2291 * @param name 2292 * The <a href="#binary-name">package name</a> 2293 * 2294 * @return The {@code Package} of the given name that has been defined by 2295 * this class loader or its ancestors, or {@code null} if not found. 2296 * 2297 * @throws NullPointerException 2298 * if {@code name} is {@code null}. 2299 * 2300 * @deprecated 2301 * If multiple class loaders delegate to each other and define classes 2302 * with the same package name, and one such loader relies on the lookup 2303 * behavior of {@code getPackage} to return a {@code Package} from 2304 * a parent loader, then the properties exposed by the {@code Package} 2305 * may not be as expected in the rest of the program. 2306 * For example, the {@code Package} will only expose annotations from the 2307 * {@code package-info.class} file defined by the parent loader, even if 2308 * annotations exist in a {@code package-info.class} file defined by 2309 * a child loader. A more robust approach is to use the 2310 * {@link ClassLoader#getDefinedPackage} method which returns 2311 * a {@code Package} for the specified class loader. 2312 * 2313 * @see ClassLoader#getDefinedPackage(String) 2314 * 2315 * @since 1.2 2316 * @revised 9 2317 * @spec JPMS 2318 */ 2319 @Deprecated(since="9") 2320 protected Package getPackage(String name) { 2321 Package pkg = getDefinedPackage(name); 2322 if (pkg == null) { 2323 if (parent != null) { 2324 pkg = parent.getPackage(name); 2325 } else { 2326 pkg = BootLoader.getDefinedPackage(name); 2327 } 2328 } 2329 return pkg; 2330 } 2331 2332 /** 2333 * Returns all of the {@code Package}s that have been defined by 2334 * this class loader and its ancestors. The returned array may contain 2335 * more than one {@code Package} object of the same package name, each 2336 * defined by a different class loader in the class loader hierarchy. 2337 * 2338 * @apiNote The {@link #getPlatformClassLoader() platform class loader} 2339 * may delegate to the application class loader. In other words, 2340 * packages in modules defined to the application class loader may be 2341 * visible to the platform class loader. On the other hand, 2342 * the application class loader is not its ancestor and hence 2343 * when invoked on the platform class loader, this method will not 2344 * return any packages defined to the application class loader. 2345 * 2346 * @return The array of {@code Package} objects that have been defined by 2347 * this class loader and its ancestors 2348 * 2349 * @see ClassLoader#getDefinedPackages() 2350 * 2351 * @since 1.2 2352 * @revised 9 2353 * @spec JPMS 2354 */ 2355 protected Package[] getPackages() { 2356 Stream<Package> pkgs = packages(); 2357 ClassLoader ld = parent; 2358 while (ld != null) { 2359 pkgs = Stream.concat(ld.packages(), pkgs); 2360 ld = ld.parent; 2361 } 2362 return Stream.concat(BootLoader.packages(), pkgs) 2363 .toArray(Package[]::new); 2364 } 2365 2366 2367 2368 // package-private 2369 2370 /** 2371 * Returns a stream of Packages defined in this class loader 2372 */ 2373 Stream<Package> packages() { 2374 return packages.values().stream() 2375 .map(p -> definePackage(p.packageName(), p.module())); 2376 } 2377 2378 // -- Native library access -- 2379 2380 /** 2381 * Returns the absolute path name of a native library. The VM invokes this 2382 * method to locate the native libraries that belong to classes loaded with 2383 * this class loader. If this method returns {@code null}, the VM 2384 * searches the library along the path specified as the 2385 * "{@code java.library.path}" property. 2386 * 2387 * @param libname 2388 * The library name 2389 * 2390 * @return The absolute path of the native library 2391 * 2392 * @see System#loadLibrary(String) 2393 * @see System#mapLibraryName(String) 2394 * 2395 * @since 1.2 2396 */ 2397 protected String findLibrary(String libname) { 2398 return null; 2399 } 2400 2401 private final NativeLibraries libraries = NativeLibraries.jniNativeLibraries(this); 2402 2403 // Invoked in the java.lang.Runtime class to implement load and loadLibrary. 2404 static NativeLibrary loadLibrary(Class<?> fromClass, File file) { 2405 ClassLoader loader = (fromClass == null) ? null : fromClass.getClassLoader(); 2406 NativeLibraries libs = loader != null ? loader.libraries : BootLoader.getNativeLibraries(); 2407 NativeLibrary nl = libs.loadLibrary(fromClass, file); 2408 if (nl != null) { 2409 return nl; 2410 } 2411 throw new UnsatisfiedLinkError("Can't load library: " + file); 2412 } 2413 static NativeLibrary loadLibrary(Class<?> fromClass, String name) { 2414 ClassLoader loader = (fromClass == null) ? null : fromClass.getClassLoader(); 2415 if (loader == null) { 2416 NativeLibrary nl = BootLoader.getNativeLibraries().loadLibrary(fromClass, name); 2417 if (nl != null) { 2418 return nl; 2419 } 2420 throw new UnsatisfiedLinkError("no " + name + 2421 " in system library path: " + StaticProperty.sunBootLibraryPath()); 2422 } 2423 2424 NativeLibraries libs = loader.libraries; 2425 // First load from the file returned from ClassLoader::findLibrary, if found. 2426 String libfilename = loader.findLibrary(name); 2427 if (libfilename != null) { 2428 File libfile = new File(libfilename); 2429 if (!libfile.isAbsolute()) { 2430 throw new UnsatisfiedLinkError( 2431 "ClassLoader.findLibrary failed to return an absolute path: " + libfilename); 2432 } 2433 NativeLibrary nl = libs.loadLibrary(fromClass, libfile); 2434 if (nl != null) { 2435 return nl; 2436 } 2437 throw new UnsatisfiedLinkError("Can't load " + libfilename); 2438 } 2439 // Then load from system library path and java library path 2440 NativeLibrary nl = libs.loadLibrary(fromClass, name); 2441 if (nl != null) { 2442 return nl; 2443 } 2444 2445 // Oops, it failed 2446 throw new UnsatisfiedLinkError("no " + name + 2447 " in java.library.path: " + StaticProperty.javaLibraryPath()); 2448 } 2449 2450 /* 2451 * Invoked in the VM class linking code. 2452 */ 2453 private static long findNative(ClassLoader loader, String entryName) { 2454 if (loader == null) { 2455 return BootLoader.getNativeLibraries().find(entryName); 2456 } else { 2457 return loader.libraries.find(entryName); 2458 } 2459 } 2460 2461 // -- Assertion management -- 2462 2463 final Object assertionLock; 2464 2465 // The default toggle for assertion checking. 2466 // @GuardedBy("assertionLock") 2467 private boolean defaultAssertionStatus = false; 2468 2469 // Maps String packageName to Boolean package default assertion status Note 2470 // that the default package is placed under a null map key. If this field 2471 // is null then we are delegating assertion status queries to the VM, i.e., 2472 // none of this ClassLoader's assertion status modification methods have 2473 // been invoked. 2474 // @GuardedBy("assertionLock") 2475 private Map<String, Boolean> packageAssertionStatus = null; 2476 2477 // Maps String fullyQualifiedClassName to Boolean assertionStatus If this 2478 // field is null then we are delegating assertion status queries to the VM, 2479 // i.e., none of this ClassLoader's assertion status modification methods 2480 // have been invoked. 2481 // @GuardedBy("assertionLock") 2482 Map<String, Boolean> classAssertionStatus = null; 2483 2484 /** 2485 * Sets the default assertion status for this class loader. This setting 2486 * determines whether classes loaded by this class loader and initialized 2487 * in the future will have assertions enabled or disabled by default. 2488 * This setting may be overridden on a per-package or per-class basis by 2489 * invoking {@link #setPackageAssertionStatus(String, boolean)} or {@link 2490 * #setClassAssertionStatus(String, boolean)}. 2491 * 2492 * @param enabled 2493 * {@code true} if classes loaded by this class loader will 2494 * henceforth have assertions enabled by default, {@code false} 2495 * if they will have assertions disabled by default. 2496 * 2497 * @since 1.4 2498 */ 2499 public void setDefaultAssertionStatus(boolean enabled) { 2500 synchronized (assertionLock) { 2501 if (classAssertionStatus == null) 2502 initializeJavaAssertionMaps(); 2503 2504 defaultAssertionStatus = enabled; 2505 } 2506 } 2507 2508 /** 2509 * Sets the package default assertion status for the named package. The 2510 * package default assertion status determines the assertion status for 2511 * classes initialized in the future that belong to the named package or 2512 * any of its "subpackages". 2513 * 2514 * <p> A subpackage of a package named p is any package whose name begins 2515 * with "{@code p.}". For example, {@code javax.swing.text} is a 2516 * subpackage of {@code javax.swing}, and both {@code java.util} and 2517 * {@code java.lang.reflect} are subpackages of {@code java}. 2518 * 2519 * <p> In the event that multiple package defaults apply to a given class, 2520 * the package default pertaining to the most specific package takes 2521 * precedence over the others. For example, if {@code javax.lang} and 2522 * {@code javax.lang.reflect} both have package defaults associated with 2523 * them, the latter package default applies to classes in 2524 * {@code javax.lang.reflect}. 2525 * 2526 * <p> Package defaults take precedence over the class loader's default 2527 * assertion status, and may be overridden on a per-class basis by invoking 2528 * {@link #setClassAssertionStatus(String, boolean)}. </p> 2529 * 2530 * @param packageName 2531 * The name of the package whose package default assertion status 2532 * is to be set. A {@code null} value indicates the unnamed 2533 * package that is "current" 2534 * (see section 7.4.2 of 2535 * <cite>The Java Language Specification</cite>.) 2536 * 2537 * @param enabled 2538 * {@code true} if classes loaded by this classloader and 2539 * belonging to the named package or any of its subpackages will 2540 * have assertions enabled by default, {@code false} if they will 2541 * have assertions disabled by default. 2542 * 2543 * @since 1.4 2544 */ 2545 public void setPackageAssertionStatus(String packageName, 2546 boolean enabled) { 2547 synchronized (assertionLock) { 2548 if (packageAssertionStatus == null) 2549 initializeJavaAssertionMaps(); 2550 2551 packageAssertionStatus.put(packageName, enabled); 2552 } 2553 } 2554 2555 /** 2556 * Sets the desired assertion status for the named top-level class in this 2557 * class loader and any nested classes contained therein. This setting 2558 * takes precedence over the class loader's default assertion status, and 2559 * over any applicable per-package default. This method has no effect if 2560 * the named class has already been initialized. (Once a class is 2561 * initialized, its assertion status cannot change.) 2562 * 2563 * <p> If the named class is not a top-level class, this invocation will 2564 * have no effect on the actual assertion status of any class. </p> 2565 * 2566 * @param className 2567 * The fully qualified class name of the top-level class whose 2568 * assertion status is to be set. 2569 * 2570 * @param enabled 2571 * {@code true} if the named class is to have assertions 2572 * enabled when (and if) it is initialized, {@code false} if the 2573 * class is to have assertions disabled. 2574 * 2575 * @since 1.4 2576 */ 2577 public void setClassAssertionStatus(String className, boolean enabled) { 2578 synchronized (assertionLock) { 2579 if (classAssertionStatus == null) 2580 initializeJavaAssertionMaps(); 2581 2582 classAssertionStatus.put(className, enabled); 2583 } 2584 } 2585 2586 /** 2587 * Sets the default assertion status for this class loader to 2588 * {@code false} and discards any package defaults or class assertion 2589 * status settings associated with the class loader. This method is 2590 * provided so that class loaders can be made to ignore any command line or 2591 * persistent assertion status settings and "start with a clean slate." 2592 * 2593 * @since 1.4 2594 */ 2595 public void clearAssertionStatus() { 2596 /* 2597 * Whether or not "Java assertion maps" are initialized, set 2598 * them to empty maps, effectively ignoring any present settings. 2599 */ 2600 synchronized (assertionLock) { 2601 classAssertionStatus = new HashMap<>(); 2602 packageAssertionStatus = new HashMap<>(); 2603 defaultAssertionStatus = false; 2604 } 2605 } 2606 2607 /** 2608 * Returns the assertion status that would be assigned to the specified 2609 * class if it were to be initialized at the time this method is invoked. 2610 * If the named class has had its assertion status set, the most recent 2611 * setting will be returned; otherwise, if any package default assertion 2612 * status pertains to this class, the most recent setting for the most 2613 * specific pertinent package default assertion status is returned; 2614 * otherwise, this class loader's default assertion status is returned. 2615 * </p> 2616 * 2617 * @param className 2618 * The fully qualified class name of the class whose desired 2619 * assertion status is being queried. 2620 * 2621 * @return The desired assertion status of the specified class. 2622 * 2623 * @see #setClassAssertionStatus(String, boolean) 2624 * @see #setPackageAssertionStatus(String, boolean) 2625 * @see #setDefaultAssertionStatus(boolean) 2626 * 2627 * @since 1.4 2628 */ 2629 boolean desiredAssertionStatus(String className) { 2630 synchronized (assertionLock) { 2631 // assert classAssertionStatus != null; 2632 // assert packageAssertionStatus != null; 2633 2634 // Check for a class entry 2635 Boolean result = classAssertionStatus.get(className); 2636 if (result != null) 2637 return result.booleanValue(); 2638 2639 // Check for most specific package entry 2640 int dotIndex = className.lastIndexOf('.'); 2641 if (dotIndex < 0) { // default package 2642 result = packageAssertionStatus.get(null); 2643 if (result != null) 2644 return result.booleanValue(); 2645 } 2646 while(dotIndex > 0) { 2647 className = className.substring(0, dotIndex); 2648 result = packageAssertionStatus.get(className); 2649 if (result != null) 2650 return result.booleanValue(); 2651 dotIndex = className.lastIndexOf('.', dotIndex-1); 2652 } 2653 2654 // Return the classloader default 2655 return defaultAssertionStatus; 2656 } 2657 } 2658 2659 // Set up the assertions with information provided by the VM. 2660 // Note: Should only be called inside a synchronized block 2661 private void initializeJavaAssertionMaps() { 2662 // assert Thread.holdsLock(assertionLock); 2663 2664 classAssertionStatus = new HashMap<>(); 2665 packageAssertionStatus = new HashMap<>(); 2666 AssertionStatusDirectives directives = retrieveDirectives(); 2667 2668 for(int i = 0; i < directives.classes.length; i++) 2669 classAssertionStatus.put(directives.classes[i], 2670 directives.classEnabled[i]); 2671 2672 for(int i = 0; i < directives.packages.length; i++) 2673 packageAssertionStatus.put(directives.packages[i], 2674 directives.packageEnabled[i]); 2675 2676 defaultAssertionStatus = directives.deflt; 2677 } 2678 2679 // Retrieves the assertion directives from the VM. 2680 private static native AssertionStatusDirectives retrieveDirectives(); 2681 2682 2683 // -- Misc -- 2684 2685 /** 2686 * Returns the ConcurrentHashMap used as a storage for ClassLoaderValue(s) 2687 * associated with this ClassLoader, creating it if it doesn't already exist. 2688 */ 2689 ConcurrentHashMap<?, ?> createOrGetClassLoaderValueMap() { 2690 ConcurrentHashMap<?, ?> map = classLoaderValueMap; 2691 if (map == null) { 2692 map = new ConcurrentHashMap<>(); 2693 boolean set = trySetObjectField("classLoaderValueMap", map); 2694 if (!set) { 2695 // beaten by someone else 2696 map = classLoaderValueMap; 2697 } 2698 } 2699 return map; 2700 } 2701 2702 // the storage for ClassLoaderValue(s) associated with this ClassLoader 2703 private volatile ConcurrentHashMap<?, ?> classLoaderValueMap; 2704 2705 /** 2706 * Attempts to atomically set a volatile field in this object. Returns 2707 * {@code true} if not beaten by another thread. Avoids the use of 2708 * AtomicReferenceFieldUpdater in this class. 2709 */ 2710 private boolean trySetObjectField(String name, Object obj) { 2711 Unsafe unsafe = Unsafe.getUnsafe(); 2712 Class<?> k = ClassLoader.class; 2713 long offset; 2714 offset = unsafe.objectFieldOffset(k, name); 2715 return unsafe.compareAndSetReference(this, offset, null, obj); 2716 } 2717 } 2718 2719 /* 2720 * A utility class that will enumerate over an array of enumerations. 2721 */ 2722 final class CompoundEnumeration<E> implements Enumeration<E> { 2723 private final Enumeration<E>[] enums; 2724 private int index; 2725 2726 public CompoundEnumeration(Enumeration<E>[] enums) { 2727 this.enums = enums; 2728 } 2729 2730 private boolean next() { 2731 while (index < enums.length) { 2732 if (enums[index] != null && enums[index].hasMoreElements()) { 2733 return true; 2734 } 2735 index++; 2736 } 2737 return false; 2738 } 2739 2740 public boolean hasMoreElements() { 2741 return next(); 2742 } 2743 2744 public E nextElement() { 2745 if (!next()) { 2746 throw new NoSuchElementException(); 2747 } 2748 return enums[index].nextElement(); 2749 } 2750 }