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