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