< prev index next >

src/java.base/share/classes/java/lang/ClassLoader.java

Print this page




  53 import java.util.Vector;
  54 import java.util.WeakHashMap;
  55 import java.util.concurrent.ConcurrentHashMap;
  56 import java.util.function.Supplier;
  57 import java.util.stream.Stream;
  58 import java.util.stream.StreamSupport;
  59 
  60 import jdk.internal.perf.PerfCounter;
  61 import jdk.internal.loader.BootLoader;
  62 import jdk.internal.loader.ClassLoaders;
  63 import jdk.internal.misc.SharedSecrets;
  64 import jdk.internal.misc.Unsafe;
  65 import jdk.internal.misc.VM;
  66 import jdk.internal.reflect.CallerSensitive;
  67 import jdk.internal.reflect.Reflection;
  68 import sun.reflect.misc.ReflectUtil;
  69 import sun.security.util.SecurityConstants;
  70 
  71 /**
  72  * A class loader is an object that is responsible for loading classes. The
  73  * class <tt>ClassLoader</tt> is an abstract class.  Given the <a
  74  * href="#name">binary name</a> of a class, a class loader should attempt to
  75  * locate or generate data that constitutes a definition for the class.  A
  76  * typical strategy is to transform the name into a file name and then read a
  77  * "class file" of that name from a file system.
  78  *
  79  * <p> Every {@link Class <tt>Class</tt>} object contains a {@link
  80  * Class#getClassLoader() reference} to the <tt>ClassLoader</tt> that defined
  81  * it.
  82  *
  83  * <p> <tt>Class</tt> objects for array classes are not created by class
  84  * loaders, but are created automatically as required by the Java runtime.
  85  * The class loader for an array class, as returned by {@link
  86  * Class#getClassLoader()} is the same as the class loader for its element
  87  * type; if the element type is a primitive type, then the array class has no
  88  * class loader.
  89  *
  90  * <p> Applications implement subclasses of <tt>ClassLoader</tt> in order to
  91  * extend the manner in which the Java virtual machine dynamically loads
  92  * classes.
  93  *
  94  * <p> Class loaders may typically be used by security managers to indicate
  95  * security domains.
  96  *
  97  * <p> The <tt>ClassLoader</tt> class uses a delegation model to search for
  98  * classes and resources.  Each instance of <tt>ClassLoader</tt> has an
  99  * associated parent class loader.  When requested to find a class or
 100  * resource, a <tt>ClassLoader</tt> instance will delegate the search for the
 101  * class or resource to its parent class loader before attempting to find the
 102  * class or resource itself.
 103  *
 104  * <p> Class loaders that support concurrent loading of classes are known as
 105  * <em>{@linkplain #isRegisteredAsParallelCapable() parallel capable}</em> class
 106  * loaders and are required to register themselves at their class initialization
 107  * time by invoking the {@link
 108  * #registerAsParallelCapable <tt>ClassLoader.registerAsParallelCapable</tt>}
 109  * method. Note that the <tt>ClassLoader</tt> class is registered as parallel
 110  * capable by default. However, its subclasses still need to register themselves
 111  * if they are parallel capable.
 112  * In environments in which the delegation model is not strictly
 113  * hierarchical, class loaders need to be parallel capable, otherwise class
 114  * loading can lead to deadlocks because the loader lock is held for the
 115  * duration of the class loading process (see {@link #loadClass
 116  * <tt>loadClass</tt>} methods).
 117  *
 118  * <h3> <a name="builtinLoaders">Run-time Built-in Class Loaders</a></h3>
 119  *
 120  * The Java run-time has the following built-in class loaders:
 121  *
 122  * <ul>
 123  * <li>Bootstrap class loader.
 124  *     It is the virtual machine's built-in class loader, typically represented
 125  *     as {@code null}, and does not have a parent.</li>
 126  * <li>{@linkplain #getPlatformClassLoader() Platform class loader}.
 127  *     All <em>platform classes</em> are visible to the platform class loader
 128  *     that can be used as the parent of a {@code ClassLoader} instance.
 129  *     Platform classes include Java SE platform APIs, their implementation
 130  *     classes and JDK-specific run-time classes that are defined by the
 131  *     platform class loader or its ancestors.</li>
 132  * <li>{@linkplain #getSystemClassLoader() System class loader}.
 133  *     It is also known as <em>application class
 134  *     loader</em> and is distinct from the platform class loader.
 135  *     The system class loader is typically used to define classes on the
 136  *     application class path, module path, and JDK-specific tools.
 137  *     The platform class loader is a parent or an ancestor of the system class
 138  *     loader that all platform classes are visible to it.</li>
 139  * </ul>
 140  *
 141  * <p> Normally, the Java virtual machine loads classes from the local file
 142  * system in a platform-dependent manner.
 143  * However, some classes may not originate from a file; they may originate
 144  * from other sources, such as the network, or they could be constructed by an
 145  * application.  The method {@link #defineClass(String, byte[], int, int)
 146  * <tt>defineClass</tt>} converts an array of bytes into an instance of class
 147  * <tt>Class</tt>. Instances of this newly defined class can be created using
 148  * {@link Class#newInstance <tt>Class.newInstance</tt>}.
 149  *
 150  * <p> The methods and constructors of objects created by a class loader may
 151  * reference other classes.  To determine the class(es) referred to, the Java
 152  * virtual machine invokes the {@link #loadClass <tt>loadClass</tt>} method of
 153  * the class loader that originally created the class.
 154  *
 155  * <p> For example, an application could create a network class loader to
 156  * download class files from a server.  Sample code might look like:
 157  *
 158  * <blockquote><pre>
 159  *   ClassLoader loader&nbsp;= new NetworkClassLoader(host,&nbsp;port);
 160  *   Object main&nbsp;= loader.loadClass("Main", true).newInstance();
 161  *       &nbsp;.&nbsp;.&nbsp;.
 162  * </pre></blockquote>
 163  *
 164  * <p> The network class loader subclass must define the methods {@link
 165  * #findClass <tt>findClass</tt>} and <tt>loadClassData</tt> to load a class
 166  * from the network.  Once it has downloaded the bytes that make up the class,
 167  * it should use the method {@link #defineClass <tt>defineClass</tt>} to
 168  * create a class instance.  A sample implementation is:
 169  *
 170  * <blockquote><pre>
 171  *     class NetworkClassLoader extends ClassLoader {
 172  *         String host;
 173  *         int port;
 174  *
 175  *         public Class findClass(String name) {
 176  *             byte[] b = loadClassData(name);
 177  *             return defineClass(name, b, 0, b.length);
 178  *         }
 179  *
 180  *         private byte[] loadClassData(String name) {
 181  *             // load the class data from the connection
 182  *             &nbsp;.&nbsp;.&nbsp;.
 183  *         }
 184  *     }
 185  * </pre></blockquote>
 186  *
 187  * <h3> <a name="name">Binary names</a> </h3>


 375      * @throws IllegalArgumentException if the given name is empty.
 376      *
 377      * @throws SecurityException
 378      *         If a security manager exists and its
 379      *         {@link SecurityManager#checkCreateClassLoader()}
 380      *         method doesn't allow creation of a new class loader.
 381      *
 382      * @since  9
 383      */
 384     protected ClassLoader(String name, ClassLoader parent) {
 385         this(checkCreateClassLoader(name), name, parent);
 386     }
 387 
 388 
 389     /**
 390      * Creates a new class loader using the specified parent class loader for
 391      * delegation.
 392      *
 393      * <p> If there is a security manager, its {@link
 394      * SecurityManager#checkCreateClassLoader()
 395      * <tt>checkCreateClassLoader</tt>} method is invoked.  This may result in
 396      * a security exception.  </p>
 397      *
 398      * @param  parent
 399      *         The parent class loader
 400      *
 401      * @throws  SecurityException
 402      *          If a security manager exists and its
 403      *          <tt>checkCreateClassLoader</tt> method doesn't allow creation
 404      *          of a new class loader.
 405      *
 406      * @since  1.2
 407      */
 408     protected ClassLoader(ClassLoader parent) {
 409         this(checkCreateClassLoader(), null, parent);
 410     }
 411 
 412     /**
 413      * Creates a new class loader using the <tt>ClassLoader</tt> returned by
 414      * the method {@link #getSystemClassLoader()
 415      * <tt>getSystemClassLoader()</tt>} as the parent class loader.
 416      *
 417      * <p> If there is a security manager, its {@link
 418      * SecurityManager#checkCreateClassLoader()
 419      * <tt>checkCreateClassLoader</tt>} method is invoked.  This may result in
 420      * a security exception.  </p>
 421      *
 422      * @throws  SecurityException
 423      *          If a security manager exists and its
 424      *          <tt>checkCreateClassLoader</tt> method doesn't allow creation
 425      *          of a new class loader.
 426      */
 427     protected ClassLoader() {
 428         this(checkCreateClassLoader(), null, getSystemClassLoader());
 429     }
 430 
 431     /**
 432      * Returns the name of this class loader or {@code null} if
 433      * this class loader is not named.
 434      *
 435      * @apiNote This method is non-final for compatibility.  If this
 436      * method is overridden, this method must return the same name
 437      * as specified when this class loader was instantiated.
 438      *
 439      * @return name of this class loader; or {@code null} if
 440      * this class loader is not named.
 441      *
 442      * @since 9
 443      */
 444     public String getName() {
 445         return name;
 446     }
 447 
 448     // package-private used by StackTraceElement to avoid
 449     // calling the overrideable getName method
 450     final String name() {
 451         return name;
 452     }
 453 
 454     // -- Class --
 455 
 456     /**
 457      * Loads the class with the specified <a href="#name">binary name</a>.
 458      * This method searches for classes in the same manner as the {@link
 459      * #loadClass(String, boolean)} method.  It is invoked by the Java virtual
 460      * machine to resolve class references.  Invoking this method is equivalent
 461      * to invoking {@link #loadClass(String, boolean) <tt>loadClass(name,
 462      * false)</tt>}.
 463      *
 464      * @param  name
 465      *         The <a href="#name">binary name</a> of the class
 466      *
 467      * @return  The resulting <tt>Class</tt> object
 468      *
 469      * @throws  ClassNotFoundException
 470      *          If the class was not found
 471      */
 472     public Class<?> loadClass(String name) throws ClassNotFoundException {
 473         return loadClass(name, false);
 474     }
 475 
 476     /**
 477      * Loads the class with the specified <a href="#name">binary name</a>.  The
 478      * default implementation of this method searches for classes in the
 479      * following order:
 480      *
 481      * <ol>
 482      *
 483      *   <li><p> Invoke {@link #findLoadedClass(String)} to check if the class
 484      *   has already been loaded.  </p></li>
 485      *
 486      *   <li><p> Invoke the {@link #loadClass(String) <tt>loadClass</tt>} method
 487      *   on the parent class loader.  If the parent is <tt>null</tt> the class
 488      *   loader built-in to the virtual machine is used, instead.  </p></li>
 489      *
 490      *   <li><p> Invoke the {@link #findClass(String)} method to find the
 491      *   class.  </p></li>
 492      *
 493      * </ol>
 494      *
 495      * <p> If the class was found using the above steps, and the
 496      * <tt>resolve</tt> flag is true, this method will then invoke the {@link
 497      * #resolveClass(Class)} method on the resulting <tt>Class</tt> object.
 498      *
 499      * <p> Subclasses of <tt>ClassLoader</tt> are encouraged to override {@link
 500      * #findClass(String)}, rather than this method.  </p>
 501      *
 502      * <p> Unless overridden, this method synchronizes on the result of
 503      * {@link #getClassLoadingLock <tt>getClassLoadingLock</tt>} method
 504      * during the entire class loading process.
 505      *
 506      * @param  name
 507      *         The <a href="#name">binary name</a> of the class
 508      *
 509      * @param  resolve
 510      *         If <tt>true</tt> then resolve the class
 511      *
 512      * @return  The resulting <tt>Class</tt> object
 513      *
 514      * @throws  ClassNotFoundException
 515      *          If the class could not be found
 516      */
 517     protected Class<?> loadClass(String name, boolean resolve)
 518         throws ClassNotFoundException
 519     {
 520         synchronized (getClassLoadingLock(name)) {
 521             // First, check if the class has already been loaded
 522             Class<?> c = findLoadedClass(name);
 523             if (c == null) {
 524                 long t0 = System.nanoTime();
 525                 try {
 526                     if (parent != null) {
 527                         c = parent.loadClass(name, false);
 528                     } else {
 529                         c = findBootstrapClassOrNull(name);
 530                     }
 531                 } catch (ClassNotFoundException e) {
 532                     // ClassNotFoundException thrown if class not found


 589             } else {
 590                 return null;
 591             }
 592         }
 593     }
 594 
 595     /**
 596      * Returns the lock object for class loading operations.
 597      * For backward compatibility, the default implementation of this method
 598      * behaves as follows. If this ClassLoader object is registered as
 599      * parallel capable, the method returns a dedicated object associated
 600      * with the specified class name. Otherwise, the method returns this
 601      * ClassLoader object.
 602      *
 603      * @param  className
 604      *         The name of the to-be-loaded class
 605      *
 606      * @return the lock for class loading operations
 607      *
 608      * @throws NullPointerException
 609      *         If registered as parallel capable and <tt>className</tt> is null
 610      *
 611      * @see #loadClass(String, boolean)
 612      *
 613      * @since  1.7
 614      */
 615     protected Object getClassLoadingLock(String className) {
 616         Object lock = this;
 617         if (parallelLockMap != null) {
 618             Object newLock = new Object();
 619             lock = parallelLockMap.putIfAbsent(className, newLock);
 620             if (lock == null) {
 621                 lock = newLock;
 622             }
 623         }
 624         return lock;
 625     }
 626 
 627     // This method is invoked by the virtual machine to load a class.
 628     private Class<?> loadClassInternal(String name)
 629         throws ClassNotFoundException


 650                 return;
 651             }
 652 
 653             final String name = cls.getName();
 654             final int i = name.lastIndexOf('.');
 655             if (i != -1) {
 656                 AccessController.doPrivileged(new PrivilegedAction<>() {
 657                     public Void run() {
 658                         sm.checkPackageAccess(name.substring(0, i));
 659                         return null;
 660                     }
 661                 }, new AccessControlContext(new ProtectionDomain[] {pd}));
 662             }
 663         }
 664     }
 665 
 666     /**
 667      * Finds the class with the specified <a href="#name">binary name</a>.
 668      * This method should be overridden by class loader implementations that
 669      * follow the delegation model for loading classes, and will be invoked by
 670      * the {@link #loadClass <tt>loadClass</tt>} method after checking the
 671      * parent class loader for the requested class.  The default implementation
 672      * throws a <tt>ClassNotFoundException</tt>.
 673      *
 674      * @param  name
 675      *         The <a href="#name">binary name</a> of the class
 676      *
 677      * @return  The resulting <tt>Class</tt> object
 678      *
 679      * @throws  ClassNotFoundException
 680      *          If the class could not be found
 681      *
 682      * @since  1.2
 683      */
 684     protected Class<?> findClass(String name) throws ClassNotFoundException {
 685         throw new ClassNotFoundException(name);
 686     }
 687 
 688     /**
 689      * Finds the class with the given <a href="#name">binary name</a>
 690      * in a module defined to this class loader.
 691      * Class loader implementations that support the loading from modules
 692      * should override this method.
 693      *
 694      * @apiNote This method returns {@code null} rather than throwing
 695      *          {@code ClassNotFoundException} if the class could not be found.
 696      *
 697      * @implSpec The default implementation attempts to find the class by


 705 
 706      * @param  name
 707      *         The <a href="#name">binary name</a> of the class
 708      *
 709      * @return The resulting {@code Class} object, or {@code null}
 710      *         if the class could not be found.
 711      *
 712      * @since 9
 713      */
 714     protected Class<?> findClass(String moduleName, String name) {
 715         if (moduleName == null) {
 716             try {
 717                 return findClass(name);
 718             } catch (ClassNotFoundException ignore) { }
 719         }
 720         return null;
 721     }
 722 
 723 
 724     /**
 725      * Converts an array of bytes into an instance of class <tt>Class</tt>.
 726      * Before the <tt>Class</tt> can be used it must be resolved.  This method
 727      * is deprecated in favor of the version that takes a <a
 728      * href="#name">binary name</a> as its first argument, and is more secure.
 729      *
 730      * @param  b
 731      *         The bytes that make up the class data.  The bytes in positions
 732      *         <tt>off</tt> through <tt>off+len-1</tt> should have the format
 733      *         of a valid class file as defined by
 734      *         <cite>The Java&trade; Virtual Machine Specification</cite>.
 735      *
 736      * @param  off
 737      *         The start offset in <tt>b</tt> of the class data
 738      *
 739      * @param  len
 740      *         The length of the class data
 741      *
 742      * @return  The <tt>Class</tt> object that was created from the specified
 743      *          class data
 744      *
 745      * @throws  ClassFormatError
 746      *          If the data did not contain a valid class
 747      *
 748      * @throws  IndexOutOfBoundsException
 749      *          If either <tt>off</tt> or <tt>len</tt> is negative, or if
 750      *          <tt>off+len</tt> is greater than <tt>b.length</tt>.
 751      *
 752      * @throws  SecurityException
 753      *          If an attempt is made to add this class to a package that
 754      *          contains classes that were signed by a different set of
 755      *          certificates than this class, or if an attempt is made
 756      *          to define a class in a package with a fully-qualified name
 757      *          that starts with "{@code java.}".
 758      *
 759      * @see  #loadClass(String, boolean)
 760      * @see  #resolveClass(Class)
 761      *
 762      * @deprecated  Replaced by {@link #defineClass(String, byte[], int, int)
 763      * defineClass(String, byte[], int, int)}
 764      */
 765     @Deprecated(since="1.1")
 766     protected final Class<?> defineClass(byte[] b, int off, int len)
 767         throws ClassFormatError
 768     {
 769         return defineClass(null, b, off, len, null);
 770     }


 977         Class<?> c = defineClass1(name, b, off, len, protectionDomain, source);
 978         postDefineClass(c, protectionDomain);
 979         return c;
 980     }
 981 
 982     /**
 983      * Converts a {@link java.nio.ByteBuffer ByteBuffer} into an instance
 984      * of class {@code Class}, with the given {@code ProtectionDomain}.
 985      * If the given {@code ProtectionDomain} is {@code null}, then a default
 986      * protection domain will be assigned to the class as
 987      * specified in the documentation for {@link #defineClass(String, byte[],
 988      * int, int)}.  Before the class can be used it must be resolved.
 989      *
 990      * <p>The rules about the first class defined in a package determining the
 991      * set of certificates for the package, the restrictions on class names,
 992      * and the defined package of the class
 993      * are identical to those specified in the documentation for {@link
 994      * #defineClass(String, byte[], int, int, ProtectionDomain)}.
 995      *
 996      * <p> An invocation of this method of the form
 997      * <i>cl</i><tt>.defineClass(</tt><i>name</i><tt>,</tt>
 998      * <i>bBuffer</i><tt>,</tt> <i>pd</i><tt>)</tt> yields exactly the same
 999      * result as the statements
1000      *
1001      *<p> <tt>
1002      * ...<br>
1003      * byte[] temp = new byte[bBuffer.{@link
1004      * java.nio.ByteBuffer#remaining remaining}()];<br>
1005      *     bBuffer.{@link java.nio.ByteBuffer#get(byte[])
1006      * get}(temp);<br>
1007      *     return {@link #defineClass(String, byte[], int, int, ProtectionDomain)
1008      * cl.defineClass}(name, temp, 0,
1009      * temp.length, pd);<br>
1010      * </tt></p>
1011      *
1012      * @param  name
1013      *         The expected <a href="#name">binary name</a>. of the class, or
1014      *         <tt>null</tt> if not known
1015      *
1016      * @param  b
1017      *         The bytes that make up the class data. The bytes from positions
1018      *         <tt>b.position()</tt> through <tt>b.position() + b.limit() -1
1019      *         </tt> should have the format of a valid class file as defined by
1020      *         <cite>The Java&trade; Virtual Machine Specification</cite>.
1021      *
1022      * @param  protectionDomain
1023      *         The {@code ProtectionDomain} of the class, or {@code null}.
1024      *
1025      * @return  The {@code Class} object created from the data,
1026      *          and {@code ProtectionDomain}.
1027      *
1028      * @throws  ClassFormatError
1029      *          If the data did not contain a valid class.
1030      *
1031      * @throws  NoClassDefFoundError
1032      *          If {@code name} is not {@code null} and not equal to the
1033      *          <a href="#name">binary name</a> of the class specified by {@code b}
1034      *
1035      * @throws  SecurityException
1036      *          If an attempt is made to add this class to a package that
1037      *          contains classes that were signed by a different set of
1038      *          certificates than this class, or if {@code name} begins with
1039      *          "{@code java.}".


1141             if (!match) return false;
1142         }
1143 
1144         // now do the same for pcerts
1145         for (Certificate pcert : pcerts) {
1146             match = false;
1147             for (Certificate cert : certs) {
1148                 if (pcert.equals(cert)) {
1149                     match = true;
1150                     break;
1151                 }
1152             }
1153             if (!match) return false;
1154         }
1155 
1156         return true;
1157     }
1158 
1159     /**
1160      * Links the specified class.  This (misleadingly named) method may be
1161      * used by a class loader to link a class.  If the class <tt>c</tt> has
1162      * already been linked, then this method simply returns. Otherwise, the
1163      * class is linked as described in the "Execution" chapter of
1164      * <cite>The Java&trade; Language Specification</cite>.
1165      *
1166      * @param  c
1167      *         The class to link
1168      *
1169      * @throws  NullPointerException
1170      *          If <tt>c</tt> is <tt>null</tt>.
1171      *
1172      * @see  #defineClass(String, byte[], int, int)
1173      */
1174     protected final void resolveClass(Class<?> c) {
1175         if (c == null) {
1176             throw new NullPointerException();
1177         }
1178     }
1179 
1180     /**
1181      * Finds a class with the specified <a href="#name">binary name</a>,
1182      * loading it if necessary.
1183      *
1184      * <p> This method loads the class through the system class loader (see
1185      * {@link #getSystemClassLoader()}).  The <tt>Class</tt> object returned
1186      * might have more than one <tt>ClassLoader</tt> associated with it.
1187      * Subclasses of <tt>ClassLoader</tt> need not usually invoke this method,
1188      * because most class loaders need to override just {@link
1189      * #findClass(String)}.  </p>
1190      *
1191      * @param  name
1192      *         The <a href="#name">binary name</a> of the class
1193      *
1194      * @return  The <tt>Class</tt> object for the specified <tt>name</tt>
1195      *
1196      * @throws  ClassNotFoundException
1197      *          If the class could not be found
1198      *
1199      * @see  #ClassLoader(ClassLoader)
1200      * @see  #getParent()
1201      */
1202     protected final Class<?> findSystemClass(String name)
1203         throws ClassNotFoundException
1204     {
1205         return getSystemClassLoader().loadClass(name);
1206     }
1207 
1208     /**
1209      * Returns a class loaded by the bootstrap class loader;
1210      * or return null if not found.
1211      */
1212     Class<?> findBootstrapClassOrNull(String name) {
1213         if (!checkName(name)) return null;
1214 
1215         return findBootstrapClass(name);
1216     }
1217 
1218     // return null if not found
1219     private native Class<?> findBootstrapClass(String name);
1220 
1221     /**
1222      * Returns the class with the given <a href="#name">binary name</a> if this
1223      * loader has been recorded by the Java virtual machine as an initiating
1224      * loader of a class with that <a href="#name">binary name</a>.  Otherwise
1225      * <tt>null</tt> is returned.
1226      *
1227      * @param  name
1228      *         The <a href="#name">binary name</a> of the class
1229      *
1230      * @return  The <tt>Class</tt> object, or <tt>null</tt> if the class has
1231      *          not been loaded
1232      *
1233      * @since  1.1
1234      */
1235     protected final Class<?> findLoadedClass(String name) {
1236         if (!checkName(name))
1237             return null;
1238         return findLoadedClass0(name);
1239     }
1240 
1241     private final native Class<?> findLoadedClass0(String name);
1242 
1243     /**
1244      * Sets the signers of a class.  This should be invoked after defining a
1245      * class.
1246      *
1247      * @param  c
1248      *         The <tt>Class</tt> object
1249      *
1250      * @param  signers
1251      *         The signers for the class
1252      *
1253      * @since  1.1
1254      */
1255     protected final void setSigners(Class<?> c, Object[] signers) {
1256         c.setSigners(signers);
1257     }
1258 
1259 
1260     // -- Resources --
1261 
1262     /**
1263      * Returns a URL to a resource in a module defined to this class loader.
1264      * Class loader implementations that support the loading from modules
1265      * should override this method.
1266      *
1267      * @apiNote This method is the basis for the {@code Class} {@link
1268      * Class#getResource getResource} and {@link Class#getResourceAsStream


1289      *
1290      * @throws IOException
1291      *         If I/O errors occur
1292      *
1293      * @see java.lang.module.ModuleReader#find(String)
1294      * @since 9
1295      */
1296     protected URL findResource(String moduleName, String name) throws IOException {
1297         if (moduleName == null) {
1298             return findResource(name);
1299         } else {
1300             return null;
1301         }
1302     }
1303 
1304     /**
1305      * Finds the resource with the given name.  A resource is some data
1306      * (images, audio, text, etc) that can be accessed by class code in a way
1307      * that is independent of the location of the code.
1308      *
1309      * <p> The name of a resource is a '<tt>/</tt>'-separated path name that
1310      * identifies the resource.
1311      *
1312      * <p> This method will first search the parent class loader for the
1313      * resource; if the parent is <tt>null</tt> the path of the class loader
1314      * built-in to the virtual machine is searched.  That failing, this method
1315      * will invoke {@link #findResource(String)} to find the resource.  </p>
1316      *
1317      * <p> Resources in named modules are subject to the encapsulation rules
1318      * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.
1319      * Additionally, and except for the special case where the resource has a
1320      * name ending with "{@code .class}", this method will only find resources in
1321      * packages of named modules when the package is {@link Module#isOpen(String)
1322      * opened} unconditionally (even if the caller of this method is in the
1323      * same module as the resource). </p>
1324      *
1325      * @apiNote Where several modules are defined to the same class loader,
1326      * and where more than one module contains a resource with the given name,
1327      * then the ordering that modules are searched is not specified and may be
1328      * very unpredictable.
1329      * When overriding this method it is recommended that an implementation
1330      * ensures that any delegation is consistent with the {@link
1331      * #getResources(java.lang.String) getResources(String)} method.
1332      *
1333      * @param  name


1345      */
1346     public URL getResource(String name) {
1347         Objects.requireNonNull(name);
1348         URL url;
1349         if (parent != null) {
1350             url = parent.getResource(name);
1351         } else {
1352             url = BootLoader.findResource(name);
1353         }
1354         if (url == null) {
1355             url = findResource(name);
1356         }
1357         return url;
1358     }
1359 
1360     /**
1361      * Finds all the resources with the given name. A resource is some data
1362      * (images, audio, text, etc) that can be accessed by class code in a way
1363      * that is independent of the location of the code.
1364      *
1365      * <p> The name of a resource is a <tt>/</tt>-separated path name that
1366      * identifies the resource.
1367      *
1368      * <p> The delegation order for searching is described in the documentation
1369      * for {@link #getResource(String)}.  </p>
1370      *
1371      * <p> Resources in named modules are subject to the encapsulation rules
1372      * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.
1373      * Additionally, and except for the special case where the resource has a
1374      * name ending with "{@code .class}", this method will only find resources in
1375      * packages of named modules when the package is {@link Module#isOpen(String)
1376      * opened} unconditionally (even if the caller of this method is in the
1377      * same module as the resource).</p>
1378      *
1379      * @apiNote Where several modules are defined to the same class loader,
1380      * and where more than one module contains a resource with the given name,
1381      * then the ordering is not specified and may be very unpredictable.
1382      * When overriding this method it is recommended that an
1383      * implementation ensures that any delegation is consistent with the {@link
1384      * #getResource(java.lang.String) getResource(String)} method. This should
1385      * ensure that the first element returned by the Enumeration's
1386      * {@code nextElement} method is the same resource that the
1387      * {@code getResource(String)} method would return.
1388      *
1389      * @param  name
1390      *         The resource name
1391      *
1392      * @return  An enumeration of {@link java.net.URL <tt>URL</tt>} objects for
1393      *          the resource. If no resources could  be found, the enumeration
1394      *          will be empty. Resources for which a {@code URL} cannot be
1395      *          constructed, are in package that is not opened unconditionally,
1396      *          or access to the resource is denied by the security manager,
1397      *          are not returned in the enumeration.
1398      *
1399      * @throws  IOException
1400      *          If I/O errors occur
1401      * @throws  NullPointerException If {@code name} is {@code null}
1402      *
1403      * @see  #findResources(String)
1404      *
1405      * @since  1.2
1406      */
1407     public Enumeration<URL> getResources(String name) throws IOException {
1408         Objects.requireNonNull(name);
1409         @SuppressWarnings("unchecked")
1410         Enumeration<URL>[] tmp = (Enumeration<URL>[]) new Enumeration<?>[2];
1411         if (parent != null) {
1412             tmp[0] = parent.getResources(name);


1488      * it must not find non-"{@code .class}" resources in packages of named
1489      * modules unless the package is {@link Module#isOpen(String) opened}
1490      * unconditionally. </p>
1491      *
1492      * @param  name
1493      *         The resource name
1494      *
1495      * @return  {@code URL} object for reading the resource; {@code null} if
1496      *          the resource could not be found, a {@code URL} could not be
1497      *          constructed to locate the resource, the resource is in a package
1498      *          that is not opened unconditionally, or access to the resource is
1499      *          denied by the security manager.
1500      *
1501      * @since  1.2
1502      */
1503     protected URL findResource(String name) {
1504         return null;
1505     }
1506 
1507     /**
1508      * Returns an enumeration of {@link java.net.URL <tt>URL</tt>} objects
1509      * representing all the resources with the given name. Class loader
1510      * implementations should override this method to specify where to load
1511      * resources from.
1512      *
1513      * <p> For resources in named modules then the method must implement the
1514      * rules for encapsulation specified in the {@code Module} {@link
1515      * Module#getResourceAsStream getResourceAsStream} method. Additionally,
1516      * it must not find non-"{@code .class}" resources in packages of named
1517      * modules unless the package is {@link Module#isOpen(String) opened}
1518      * unconditionally. </p>
1519      *
1520      * @param  name
1521      *         The resource name
1522      *
1523      * @return  An enumeration of {@link java.net.URL <tt>URL</tt>} objects for
1524      *          the resource. If no resources could  be found, the enumeration
1525      *          will be empty. Resources for which a {@code URL} cannot be
1526      *          constructed, are in a package that is not opened unconditionally,
1527      *          or access to the resource is denied by the security manager,
1528      *          are not returned in the enumeration.
1529      *
1530      * @throws  IOException
1531      *          If I/O errors occur
1532      *
1533      * @since  1.2
1534      */
1535     protected Enumeration<URL> findResources(String name) throws IOException {
1536         return Collections.emptyEnumeration();
1537     }
1538 
1539     /**
1540      * Registers the caller as
1541      * {@linkplain #isRegisteredAsParallelCapable() parallel capable}.
1542      * The registration succeeds if and only if all of the following
1543      * conditions are met:


1577      */
1578     public final boolean isRegisteredAsParallelCapable() {
1579         return ParallelLoaders.isRegistered(this.getClass());
1580     }
1581 
1582     /**
1583      * Find a resource of the specified name from the search path used to load
1584      * classes.  This method locates the resource through the system class
1585      * loader (see {@link #getSystemClassLoader()}).
1586      *
1587      * <p> Resources in named modules are subject to the encapsulation rules
1588      * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.
1589      * Additionally, and except for the special case where the resource has a
1590      * name ending with "{@code .class}", this method will only find resources in
1591      * packages of named modules when the package is {@link Module#isOpen(String)
1592      * opened} unconditionally. </p>
1593      *
1594      * @param  name
1595      *         The resource name
1596      *
1597      * @return  A {@link java.net.URL <tt>URL</tt>} to the resource; {@code
1598      *          null} if the resource could not be found, a URL could not be
1599      *          constructed to locate the resource, the resource is in a package
1600      *          that is not opened unconditionally or access to the resource is
1601      *          denied by the security manager.
1602      *
1603      * @since  1.1
1604      */
1605     public static URL getSystemResource(String name) {
1606         return getSystemClassLoader().getResource(name);
1607     }
1608 
1609     /**
1610      * Finds all resources of the specified name from the search path used to
1611      * load classes.  The resources thus found are returned as an
1612      * {@link java.util.Enumeration <tt>Enumeration</tt>} of {@link
1613      * java.net.URL <tt>URL</tt>} objects.
1614      *
1615      * <p> The search order is described in the documentation for {@link
1616      * #getSystemResource(String)}.  </p>
1617      *
1618      * <p> Resources in named modules are subject to the encapsulation rules
1619      * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.
1620      * Additionally, and except for the special case where the resource has a
1621      * name ending with "{@code .class}", this method will only find resources in
1622      * packages of named modules when the package is {@link Module#isOpen(String)
1623      * opened} unconditionally. </p>
1624      *
1625      * @param  name
1626      *         The resource name
1627      *
1628      * @return  An enumeration of {@link java.net.URL <tt>URL</tt>} objects for
1629      *          the resource. If no resources could  be found, the enumeration
1630      *          will be empty. Resources for which a {@code URL} cannot be
1631      *          constructed, are in a package that is not opened unconditionally,
1632      *          or access to the resource is denied by the security manager,
1633      *          are not returned in the enumeration.
1634      *
1635      * @throws  IOException
1636      *          If I/O errors occur
1637      *
1638      * @since  1.2
1639      */
1640     public static Enumeration<URL> getSystemResources(String name)
1641         throws IOException
1642     {
1643         return getSystemClassLoader().getResources(name);
1644     }
1645 
1646     /**
1647      * Returns an input stream for reading the specified resource.
1648      *


1697      *          resource could not be found, the resource is in a package that
1698      *          is not opened unconditionally, or access to the resource is
1699      *          denied by the security manager.
1700      *
1701      * @since  1.1
1702      */
1703     public static InputStream getSystemResourceAsStream(String name) {
1704         URL url = getSystemResource(name);
1705         try {
1706             return url != null ? url.openStream() : null;
1707         } catch (IOException e) {
1708             return null;
1709         }
1710     }
1711 
1712 
1713     // -- Hierarchy --
1714 
1715     /**
1716      * Returns the parent class loader for delegation. Some implementations may
1717      * use <tt>null</tt> to represent the bootstrap class loader. This method
1718      * will return <tt>null</tt> in such implementations if this class loader's
1719      * parent is the bootstrap class loader.
1720      *
1721      * @return  The parent <tt>ClassLoader</tt>
1722      *
1723      * @throws  SecurityException
1724      *          If a security manager is present, and the caller's class loader
1725      *          is not {@code null} and is not an ancestor of this class loader,
1726      *          and the caller does not have the
1727      *          {@link RuntimePermission}{@code ("getClassLoader")}
1728      *
1729      * @since  1.2
1730      */
1731     @CallerSensitive
1732     public final ClassLoader getParent() {
1733         if (parent == null)
1734             return null;
1735         SecurityManager sm = System.getSecurityManager();
1736         if (sm != null) {
1737             // Check access to the parent class loader
1738             // If the caller's class loader is same as this class loader,
1739             // permission check is performed.
1740             checkClassLoaderPermission(parent, Reflection.getCallerClass());
1741         }


1768      *          If a security manager is present, and the caller's class loader is
1769      *          not {@code null}, and the caller's class loader is not the same
1770      *          as or an ancestor of the platform class loader,
1771      *          and the caller does not have the
1772      *          {@link RuntimePermission}{@code ("getClassLoader")}
1773      *
1774      * @since 9
1775      */
1776     @CallerSensitive
1777     public static ClassLoader getPlatformClassLoader() {
1778         SecurityManager sm = System.getSecurityManager();
1779         ClassLoader loader = getBuiltinPlatformClassLoader();
1780         if (sm != null) {
1781             checkClassLoaderPermission(loader, Reflection.getCallerClass());
1782         }
1783         return loader;
1784     }
1785 
1786     /**
1787      * Returns the system class loader for delegation.  This is the default
1788      * delegation parent for new <tt>ClassLoader</tt> instances, and is
1789      * typically the class loader used to start the application.
1790      *
1791      * <p> This method is first invoked early in the runtime's startup
1792      * sequence, at which point it creates the system class loader. This
1793      * class loader will be the context class loader for the main application
1794      * thread (for example, the thread that invokes the {@code main} method of
1795      * the main class).
1796      *
1797      * <p> The default system class loader is an implementation-dependent
1798      * instance of this class.
1799      *
1800      * <p> If the system property "<tt>java.system.class.loader</tt>" is defined
1801      * when this method is first invoked then the value of that property is
1802      * taken to be the name of a class that will be returned as the system
1803      * class loader.  The class is loaded using the default system class loader
1804      * and must define a public constructor that takes a single parameter of
1805      * type <tt>ClassLoader</tt> which is used as the delegation parent.  An
1806      * instance is then created using this constructor with the default system
1807      * class loader as the parameter.  The resulting class loader is defined
1808      * to be the system class loader. During construction, the class loader
1809      * should take great care to avoid calling {@code getSystemClassLoader()}.
1810      * If circular initialization of the system class loader is detected then
1811      * an unspecified error or exception is thrown.
1812      *
1813      * @implNote The system property to override the system class loader is not
1814      * examined until the VM is almost fully initialized. Code that executes
1815      * this method during startup should take care not to cache the return
1816      * value until the system is fully initialized.
1817      *
1818      * <p> The name of the built-in system class loader is {@code "app"}.
1819      * The class path used by the built-in system class loader is determined
1820      * by the system property "{@code java.class.path}" during early
1821      * initialization of the VM. If the system property is not defined,
1822      * or its value is an empty string, then there is no class path
1823      * when the initial module is a module on the application module path,
1824      * i.e. <em>a named module</em>. If the initial module is not on
1825      * the application module path then the class path defaults to
1826      * the current working directory.
1827      *
1828      * @return  The system <tt>ClassLoader</tt> for delegation
1829      *
1830      * @throws  SecurityException
1831      *          If a security manager is present, and the caller's class loader
1832      *          is not {@code null} and is not the same as or an ancestor of the
1833      *          system class loader, and the caller does not have the
1834      *          {@link RuntimePermission}{@code ("getClassLoader")}
1835      *
1836      * @throws  IllegalStateException
1837      *          If invoked recursively during the construction of the class
1838      *          loader specified by the "<tt>java.system.class.loader</tt>"
1839      *          property.
1840      *
1841      * @throws  Error
1842      *          If the system property "<tt>java.system.class.loader</tt>"
1843      *          is defined but the named class could not be loaded, the
1844      *          provider class does not define the required constructor, or an
1845      *          exception is thrown by that constructor when it is invoked. The
1846      *          underlying cause of the error can be retrieved via the
1847      *          {@link Throwable#getCause()} method.
1848      *
1849      * @revised  1.4
1850      */
1851     @CallerSensitive
1852     public static ClassLoader getSystemClassLoader() {
1853         switch (VM.initLevel()) {
1854             case 0:
1855             case 1:
1856             case 2:
1857                 // the system class loader is the built-in app class loader during startup
1858                 return getBuiltinAppClassLoader();
1859             case 3:
1860                 throw new InternalError("getSystemClassLoader should only be called after VM booted");
1861             case 4:
1862                 // system fully initialized


2232                      .toArray(Package[]::new);
2233     }
2234 
2235 
2236 
2237     // package-private
2238 
2239     /**
2240      * Returns a stream of Packages defined in this class loader
2241      */
2242     Stream<Package> packages() {
2243         return packages.values().stream()
2244                        .map(p -> definePackage(p.packageName(), p.module()));
2245     }
2246 
2247     // -- Native library access --
2248 
2249     /**
2250      * Returns the absolute path name of a native library.  The VM invokes this
2251      * method to locate the native libraries that belong to classes loaded with
2252      * this class loader. If this method returns <tt>null</tt>, the VM
2253      * searches the library along the path specified as the
2254      * "<tt>java.library.path</tt>" property.
2255      *
2256      * @param  libname
2257      *         The library name
2258      *
2259      * @return  The absolute path of the native library
2260      *
2261      * @see  System#loadLibrary(String)
2262      * @see  System#mapLibraryName(String)
2263      *
2264      * @since  1.2
2265      */
2266     protected String findLibrary(String libname) {
2267         return null;
2268     }
2269 
2270     /**
2271      * The inner class NativeLibrary denotes a loaded native library instance.
2272      * Every classloader contains a vector of loaded native libraries in the
2273      * private field <tt>nativeLibraries</tt>.  The native libraries loaded
2274      * into the system are entered into the <tt>systemNativeLibraries</tt>
2275      * vector.
2276      *
2277      * <p> Every native library requires a particular version of JNI. This is
2278      * denoted by the private <tt>jniVersion</tt> field.  This field is set by
2279      * the VM when it loads the library, and used by the VM to pass the correct
2280      * version of JNI to the native methods.  </p>
2281      *
2282      * @see      ClassLoader
2283      * @since    1.2
2284      */
2285     static class NativeLibrary {
2286         // opaque handle to native library, used in native code.
2287         long handle;
2288         // the version of JNI environment the native library requires.
2289         private int jniVersion;
2290         // the class from which the library is loaded, also indicates
2291         // the loader this native library belongs.
2292         private final Class<?> fromClass;
2293         // the canonicalized name of the native library.
2294         // or static library name
2295         String name;
2296         // Indicates if the native library is linked into the VM
2297         boolean isBuiltin;
2298         // Indicates if the native library is loaded


2575     // been invoked.
2576     // @GuardedBy("assertionLock")
2577     private Map<String, Boolean> packageAssertionStatus = null;
2578 
2579     // Maps String fullyQualifiedClassName to Boolean assertionStatus If this
2580     // field is null then we are delegating assertion status queries to the VM,
2581     // i.e., none of this ClassLoader's assertion status modification methods
2582     // have been invoked.
2583     // @GuardedBy("assertionLock")
2584     Map<String, Boolean> classAssertionStatus = null;
2585 
2586     /**
2587      * Sets the default assertion status for this class loader.  This setting
2588      * determines whether classes loaded by this class loader and initialized
2589      * in the future will have assertions enabled or disabled by default.
2590      * This setting may be overridden on a per-package or per-class basis by
2591      * invoking {@link #setPackageAssertionStatus(String, boolean)} or {@link
2592      * #setClassAssertionStatus(String, boolean)}.
2593      *
2594      * @param  enabled
2595      *         <tt>true</tt> if classes loaded by this class loader will
2596      *         henceforth have assertions enabled by default, <tt>false</tt>
2597      *         if they will have assertions disabled by default.
2598      *
2599      * @since  1.4
2600      */
2601     public void setDefaultAssertionStatus(boolean enabled) {
2602         synchronized (assertionLock) {
2603             if (classAssertionStatus == null)
2604                 initializeJavaAssertionMaps();
2605 
2606             defaultAssertionStatus = enabled;
2607         }
2608     }
2609 
2610     /**
2611      * Sets the package default assertion status for the named package.  The
2612      * package default assertion status determines the assertion status for
2613      * classes initialized in the future that belong to the named package or
2614      * any of its "subpackages".
2615      *
2616      * <p> A subpackage of a package named p is any package whose name begins
2617      * with "<tt>p.</tt>".  For example, <tt>javax.swing.text</tt> is a
2618      * subpackage of <tt>javax.swing</tt>, and both <tt>java.util</tt> and
2619      * <tt>java.lang.reflect</tt> are subpackages of <tt>java</tt>.
2620      *
2621      * <p> In the event that multiple package defaults apply to a given class,
2622      * the package default pertaining to the most specific package takes
2623      * precedence over the others.  For example, if <tt>javax.lang</tt> and
2624      * <tt>javax.lang.reflect</tt> both have package defaults associated with
2625      * them, the latter package default applies to classes in
2626      * <tt>javax.lang.reflect</tt>.
2627      *
2628      * <p> Package defaults take precedence over the class loader's default
2629      * assertion status, and may be overridden on a per-class basis by invoking
2630      * {@link #setClassAssertionStatus(String, boolean)}.  </p>
2631      *
2632      * @param  packageName
2633      *         The name of the package whose package default assertion status
2634      *         is to be set. A <tt>null</tt> value indicates the unnamed
2635      *         package that is "current"
2636      *         (see section 7.4.2 of
2637      *         <cite>The Java&trade; Language Specification</cite>.)
2638      *
2639      * @param  enabled
2640      *         <tt>true</tt> if classes loaded by this classloader and
2641      *         belonging to the named package or any of its subpackages will
2642      *         have assertions enabled by default, <tt>false</tt> if they will
2643      *         have assertions disabled by default.
2644      *
2645      * @since  1.4
2646      */
2647     public void setPackageAssertionStatus(String packageName,
2648                                           boolean enabled) {
2649         synchronized (assertionLock) {
2650             if (packageAssertionStatus == null)
2651                 initializeJavaAssertionMaps();
2652 
2653             packageAssertionStatus.put(packageName, enabled);
2654         }
2655     }
2656 
2657     /**
2658      * Sets the desired assertion status for the named top-level class in this
2659      * class loader and any nested classes contained therein.  This setting
2660      * takes precedence over the class loader's default assertion status, and
2661      * over any applicable per-package default.  This method has no effect if
2662      * the named class has already been initialized.  (Once a class is
2663      * initialized, its assertion status cannot change.)
2664      *
2665      * <p> If the named class is not a top-level class, this invocation will
2666      * have no effect on the actual assertion status of any class. </p>
2667      *
2668      * @param  className
2669      *         The fully qualified class name of the top-level class whose
2670      *         assertion status is to be set.
2671      *
2672      * @param  enabled
2673      *         <tt>true</tt> if the named class is to have assertions
2674      *         enabled when (and if) it is initialized, <tt>false</tt> if the
2675      *         class is to have assertions disabled.
2676      *
2677      * @since  1.4
2678      */
2679     public void setClassAssertionStatus(String className, boolean enabled) {
2680         synchronized (assertionLock) {
2681             if (classAssertionStatus == null)
2682                 initializeJavaAssertionMaps();
2683 
2684             classAssertionStatus.put(className, enabled);
2685         }
2686     }
2687 
2688     /**
2689      * Sets the default assertion status for this class loader to
2690      * <tt>false</tt> and discards any package defaults or class assertion
2691      * status settings associated with the class loader.  This method is
2692      * provided so that class loaders can be made to ignore any command line or
2693      * persistent assertion status settings and "start with a clean slate."
2694      *
2695      * @since  1.4
2696      */
2697     public void clearAssertionStatus() {
2698         /*
2699          * Whether or not "Java assertion maps" are initialized, set
2700          * them to empty maps, effectively ignoring any present settings.
2701          */
2702         synchronized (assertionLock) {
2703             classAssertionStatus = new HashMap<>();
2704             packageAssertionStatus = new HashMap<>();
2705             defaultAssertionStatus = false;
2706         }
2707     }
2708 
2709     /**
2710      * Returns the assertion status that would be assigned to the specified




  53 import java.util.Vector;
  54 import java.util.WeakHashMap;
  55 import java.util.concurrent.ConcurrentHashMap;
  56 import java.util.function.Supplier;
  57 import java.util.stream.Stream;
  58 import java.util.stream.StreamSupport;
  59 
  60 import jdk.internal.perf.PerfCounter;
  61 import jdk.internal.loader.BootLoader;
  62 import jdk.internal.loader.ClassLoaders;
  63 import jdk.internal.misc.SharedSecrets;
  64 import jdk.internal.misc.Unsafe;
  65 import jdk.internal.misc.VM;
  66 import jdk.internal.reflect.CallerSensitive;
  67 import jdk.internal.reflect.Reflection;
  68 import sun.reflect.misc.ReflectUtil;
  69 import sun.security.util.SecurityConstants;
  70 
  71 /**
  72  * A class loader is an object that is responsible for loading classes. The
  73  * class {@code ClassLoader} is an abstract class.  Given the <a
  74  * href="#name">binary name</a> of a class, a class loader should attempt to
  75  * locate or generate data that constitutes a definition for the class.  A
  76  * typical strategy is to transform the name into a file name and then read a
  77  * "class file" of that name from a file system.
  78  *
  79  * <p> Every {@link java.lang.Class Class} object contains a {@link
  80  * Class#getClassLoader() reference} to the {@code ClassLoader} that defined
  81  * it.
  82  *
  83  * <p> {@code Class} objects for array classes are not created by class
  84  * loaders, but are created automatically as required by the Java runtime.
  85  * The class loader for an array class, as returned by {@link
  86  * Class#getClassLoader()} is the same as the class loader for its element
  87  * type; if the element type is a primitive type, then the array class has no
  88  * class loader.
  89  *
  90  * <p> Applications implement subclasses of {@code ClassLoader} in order to
  91  * extend the manner in which the Java virtual machine dynamically loads
  92  * classes.
  93  *
  94  * <p> Class loaders may typically be used by security managers to indicate
  95  * security domains.
  96  *
  97  * <p> The {@code ClassLoader} class uses a delegation model to search for
  98  * classes and resources.  Each instance of {@code ClassLoader} has an
  99  * associated parent class loader.  When requested to find a class or
 100  * resource, a {@code ClassLoader} instance will delegate the search for the
 101  * class or resource to its parent class loader before attempting to find the
 102  * class or resource itself.
 103  *
 104  * <p> Class loaders that support concurrent loading of classes are known as
 105  * <em>{@linkplain #isRegisteredAsParallelCapable() parallel capable}</em> class
 106  * loaders and are required to register themselves at their class initialization
 107  * time by invoking the {@link
 108  * #registerAsParallelCapable ClassLoader.registerAsParallelCapable}
 109  * method. Note that the {@code ClassLoader} class is registered as parallel
 110  * capable by default. However, its subclasses still need to register themselves
 111  * if they are parallel capable.
 112  * In environments in which the delegation model is not strictly
 113  * hierarchical, class loaders need to be parallel capable, otherwise class
 114  * loading can lead to deadlocks because the loader lock is held for the
 115  * duration of the class loading process (see {@link #loadClass
 116  * loadClass} methods).
 117  *
 118  * <h3> <a name="builtinLoaders">Run-time Built-in Class Loaders</a></h3>
 119  *
 120  * The Java run-time has the following built-in class loaders:
 121  *
 122  * <ul>
 123  * <li>Bootstrap class loader.
 124  *     It is the virtual machine's built-in class loader, typically represented
 125  *     as {@code null}, and does not have a parent.</li>
 126  * <li>{@linkplain #getPlatformClassLoader() Platform class loader}.
 127  *     All <em>platform classes</em> are visible to the platform class loader
 128  *     that can be used as the parent of a {@code ClassLoader} instance.
 129  *     Platform classes include Java SE platform APIs, their implementation
 130  *     classes and JDK-specific run-time classes that are defined by the
 131  *     platform class loader or its ancestors.</li>
 132  * <li>{@linkplain #getSystemClassLoader() System class loader}.
 133  *     It is also known as <em>application class
 134  *     loader</em> and is distinct from the platform class loader.
 135  *     The system class loader is typically used to define classes on the
 136  *     application class path, module path, and JDK-specific tools.
 137  *     The platform class loader is a parent or an ancestor of the system class
 138  *     loader that all platform classes are visible to it.</li>
 139  * </ul>
 140  *
 141  * <p> Normally, the Java virtual machine loads classes from the local file
 142  * system in a platform-dependent manner.
 143  * However, some classes may not originate from a file; they may originate
 144  * from other sources, such as the network, or they could be constructed by an
 145  * application.  The method {@link #defineClass(String, byte[], int, int)
 146  * defineClass} converts an array of bytes into an instance of class
 147  * {@code Class}. Instances of this newly defined class can be created using
 148  * {@link Class#newInstance Class.newInstance}.
 149  *
 150  * <p> The methods and constructors of objects created by a class loader may
 151  * reference other classes.  To determine the class(es) referred to, the Java
 152  * virtual machine invokes the {@link #loadClass loadClass} method of
 153  * the class loader that originally created the class.
 154  *
 155  * <p> For example, an application could create a network class loader to
 156  * download class files from a server.  Sample code might look like:
 157  *
 158  * <blockquote><pre>
 159  *   ClassLoader loader&nbsp;= new NetworkClassLoader(host,&nbsp;port);
 160  *   Object main&nbsp;= loader.loadClass("Main", true).newInstance();
 161  *       &nbsp;.&nbsp;.&nbsp;.
 162  * </pre></blockquote>
 163  *
 164  * <p> The network class loader subclass must define the methods {@link
 165  * #findClass findClass} and {@code loadClassData} to load a class
 166  * from the network.  Once it has downloaded the bytes that make up the class,
 167  * it should use the method {@link #defineClass defineClass} to
 168  * create a class instance.  A sample implementation is:
 169  *
 170  * <blockquote><pre>
 171  *     class NetworkClassLoader extends ClassLoader {
 172  *         String host;
 173  *         int port;
 174  *
 175  *         public Class findClass(String name) {
 176  *             byte[] b = loadClassData(name);
 177  *             return defineClass(name, b, 0, b.length);
 178  *         }
 179  *
 180  *         private byte[] loadClassData(String name) {
 181  *             // load the class data from the connection
 182  *             &nbsp;.&nbsp;.&nbsp;.
 183  *         }
 184  *     }
 185  * </pre></blockquote>
 186  *
 187  * <h3> <a name="name">Binary names</a> </h3>


 375      * @throws IllegalArgumentException if the given name is empty.
 376      *
 377      * @throws SecurityException
 378      *         If a security manager exists and its
 379      *         {@link SecurityManager#checkCreateClassLoader()}
 380      *         method doesn't allow creation of a new class loader.
 381      *
 382      * @since  9
 383      */
 384     protected ClassLoader(String name, ClassLoader parent) {
 385         this(checkCreateClassLoader(name), name, parent);
 386     }
 387 
 388 
 389     /**
 390      * Creates a new class loader using the specified parent class loader for
 391      * delegation.
 392      *
 393      * <p> If there is a security manager, its {@link
 394      * SecurityManager#checkCreateClassLoader()
 395      * checkCreateClassLoader} method is invoked.  This may result in
 396      * a security exception.  </p>
 397      *
 398      * @param  parent
 399      *         The parent class loader
 400      *
 401      * @throws  SecurityException
 402      *          If a security manager exists and its
 403      *          {@code checkCreateClassLoader} method doesn't allow creation
 404      *          of a new class loader.
 405      *
 406      * @since  1.2
 407      */
 408     protected ClassLoader(ClassLoader parent) {
 409         this(checkCreateClassLoader(), null, parent);
 410     }
 411 
 412     /**
 413      * Creates a new class loader using the {@code ClassLoader} returned by
 414      * the method {@link #getSystemClassLoader()
 415      * getSystemClassLoader()} as the parent class loader.
 416      *
 417      * <p> If there is a security manager, its {@link
 418      * SecurityManager#checkCreateClassLoader()
 419      * checkCreateClassLoader} method is invoked.  This may result in
 420      * a security exception.  </p>
 421      *
 422      * @throws  SecurityException
 423      *          If a security manager exists and its
 424      *          {@code checkCreateClassLoader} method doesn't allow creation
 425      *          of a new class loader.
 426      */
 427     protected ClassLoader() {
 428         this(checkCreateClassLoader(), null, getSystemClassLoader());
 429     }
 430 
 431     /**
 432      * Returns the name of this class loader or {@code null} if
 433      * this class loader is not named.
 434      *
 435      * @apiNote This method is non-final for compatibility.  If this
 436      * method is overridden, this method must return the same name
 437      * as specified when this class loader was instantiated.
 438      *
 439      * @return name of this class loader; or {@code null} if
 440      * this class loader is not named.
 441      *
 442      * @since 9
 443      */
 444     public String getName() {
 445         return name;
 446     }
 447 
 448     // package-private used by StackTraceElement to avoid
 449     // calling the overrideable getName method
 450     final String name() {
 451         return name;
 452     }
 453 
 454     // -- Class --
 455 
 456     /**
 457      * Loads the class with the specified <a href="#name">binary name</a>.
 458      * This method searches for classes in the same manner as the {@link
 459      * #loadClass(String, boolean)} method.  It is invoked by the Java virtual
 460      * machine to resolve class references.  Invoking this method is equivalent
 461      * to invoking {@link #loadClass(String, boolean) loadClass(name,
 462      * false)}.
 463      *
 464      * @param  name
 465      *         The <a href="#name">binary name</a> of the class
 466      *
 467      * @return  The resulting {@code Class} object
 468      *
 469      * @throws  ClassNotFoundException
 470      *          If the class was not found
 471      */
 472     public Class<?> loadClass(String name) throws ClassNotFoundException {
 473         return loadClass(name, false);
 474     }
 475 
 476     /**
 477      * Loads the class with the specified <a href="#name">binary name</a>.  The
 478      * default implementation of this method searches for classes in the
 479      * following order:
 480      *
 481      * <ol>
 482      *
 483      *   <li><p> Invoke {@link #findLoadedClass(String)} to check if the class
 484      *   has already been loaded.  </p></li>
 485      *
 486      *   <li><p> Invoke the {@link #loadClass(String) loadClass} method
 487      *   on the parent class loader.  If the parent is {@code null} the class
 488      *   loader built-in to the virtual machine is used, instead.  </p></li>
 489      *
 490      *   <li><p> Invoke the {@link #findClass(String)} method to find the
 491      *   class.  </p></li>
 492      *
 493      * </ol>
 494      *
 495      * <p> If the class was found using the above steps, and the
 496      * {@code resolve} flag is true, this method will then invoke the {@link
 497      * #resolveClass(Class)} method on the resulting {@code Class} object.
 498      *
 499      * <p> Subclasses of {@code ClassLoader} are encouraged to override {@link
 500      * #findClass(String)}, rather than this method.  </p>
 501      *
 502      * <p> Unless overridden, this method synchronizes on the result of
 503      * {@link #getClassLoadingLock getClassLoadingLock} method
 504      * during the entire class loading process.
 505      *
 506      * @param  name
 507      *         The <a href="#name">binary name</a> of the class
 508      *
 509      * @param  resolve
 510      *         If {@code true} then resolve the class
 511      *
 512      * @return  The resulting {@code Class} object
 513      *
 514      * @throws  ClassNotFoundException
 515      *          If the class could not be found
 516      */
 517     protected Class<?> loadClass(String name, boolean resolve)
 518         throws ClassNotFoundException
 519     {
 520         synchronized (getClassLoadingLock(name)) {
 521             // First, check if the class has already been loaded
 522             Class<?> c = findLoadedClass(name);
 523             if (c == null) {
 524                 long t0 = System.nanoTime();
 525                 try {
 526                     if (parent != null) {
 527                         c = parent.loadClass(name, false);
 528                     } else {
 529                         c = findBootstrapClassOrNull(name);
 530                     }
 531                 } catch (ClassNotFoundException e) {
 532                     // ClassNotFoundException thrown if class not found


 589             } else {
 590                 return null;
 591             }
 592         }
 593     }
 594 
 595     /**
 596      * Returns the lock object for class loading operations.
 597      * For backward compatibility, the default implementation of this method
 598      * behaves as follows. If this ClassLoader object is registered as
 599      * parallel capable, the method returns a dedicated object associated
 600      * with the specified class name. Otherwise, the method returns this
 601      * ClassLoader object.
 602      *
 603      * @param  className
 604      *         The name of the to-be-loaded class
 605      *
 606      * @return the lock for class loading operations
 607      *
 608      * @throws NullPointerException
 609      *         If registered as parallel capable and {@code className} is null
 610      *
 611      * @see #loadClass(String, boolean)
 612      *
 613      * @since  1.7
 614      */
 615     protected Object getClassLoadingLock(String className) {
 616         Object lock = this;
 617         if (parallelLockMap != null) {
 618             Object newLock = new Object();
 619             lock = parallelLockMap.putIfAbsent(className, newLock);
 620             if (lock == null) {
 621                 lock = newLock;
 622             }
 623         }
 624         return lock;
 625     }
 626 
 627     // This method is invoked by the virtual machine to load a class.
 628     private Class<?> loadClassInternal(String name)
 629         throws ClassNotFoundException


 650                 return;
 651             }
 652 
 653             final String name = cls.getName();
 654             final int i = name.lastIndexOf('.');
 655             if (i != -1) {
 656                 AccessController.doPrivileged(new PrivilegedAction<>() {
 657                     public Void run() {
 658                         sm.checkPackageAccess(name.substring(0, i));
 659                         return null;
 660                     }
 661                 }, new AccessControlContext(new ProtectionDomain[] {pd}));
 662             }
 663         }
 664     }
 665 
 666     /**
 667      * Finds the class with the specified <a href="#name">binary name</a>.
 668      * This method should be overridden by class loader implementations that
 669      * follow the delegation model for loading classes, and will be invoked by
 670      * the {@link #loadClass loadClass} method after checking the
 671      * parent class loader for the requested class.  The default implementation
 672      * throws a {@code ClassNotFoundException}.
 673      *
 674      * @param  name
 675      *         The <a href="#name">binary name</a> of the class
 676      *
 677      * @return  The resulting {@code Class} object
 678      *
 679      * @throws  ClassNotFoundException
 680      *          If the class could not be found
 681      *
 682      * @since  1.2
 683      */
 684     protected Class<?> findClass(String name) throws ClassNotFoundException {
 685         throw new ClassNotFoundException(name);
 686     }
 687 
 688     /**
 689      * Finds the class with the given <a href="#name">binary name</a>
 690      * in a module defined to this class loader.
 691      * Class loader implementations that support the loading from modules
 692      * should override this method.
 693      *
 694      * @apiNote This method returns {@code null} rather than throwing
 695      *          {@code ClassNotFoundException} if the class could not be found.
 696      *
 697      * @implSpec The default implementation attempts to find the class by


 705 
 706      * @param  name
 707      *         The <a href="#name">binary name</a> of the class
 708      *
 709      * @return The resulting {@code Class} object, or {@code null}
 710      *         if the class could not be found.
 711      *
 712      * @since 9
 713      */
 714     protected Class<?> findClass(String moduleName, String name) {
 715         if (moduleName == null) {
 716             try {
 717                 return findClass(name);
 718             } catch (ClassNotFoundException ignore) { }
 719         }
 720         return null;
 721     }
 722 
 723 
 724     /**
 725      * Converts an array of bytes into an instance of class {@code Class}.
 726      * Before the {@code Class} can be used it must be resolved.  This method
 727      * is deprecated in favor of the version that takes a <a
 728      * href="#name">binary name</a> as its first argument, and is more secure.
 729      *
 730      * @param  b
 731      *         The bytes that make up the class data.  The bytes in positions
 732      *         {@code off} through {@code off+len-1} should have the format
 733      *         of a valid class file as defined by
 734      *         <cite>The Java&trade; Virtual Machine Specification</cite>.
 735      *
 736      * @param  off
 737      *         The start offset in {@code b} of the class data
 738      *
 739      * @param  len
 740      *         The length of the class data
 741      *
 742      * @return  The {@code Class} object that was created from the specified
 743      *          class data
 744      *
 745      * @throws  ClassFormatError
 746      *          If the data did not contain a valid class
 747      *
 748      * @throws  IndexOutOfBoundsException
 749      *          If either {@code off} or {@code len} is negative, or if
 750      *          {@code off+len} is greater than {@code b.length}.
 751      *
 752      * @throws  SecurityException
 753      *          If an attempt is made to add this class to a package that
 754      *          contains classes that were signed by a different set of
 755      *          certificates than this class, or if an attempt is made
 756      *          to define a class in a package with a fully-qualified name
 757      *          that starts with "{@code java.}".
 758      *
 759      * @see  #loadClass(String, boolean)
 760      * @see  #resolveClass(Class)
 761      *
 762      * @deprecated  Replaced by {@link #defineClass(String, byte[], int, int)
 763      * defineClass(String, byte[], int, int)}
 764      */
 765     @Deprecated(since="1.1")
 766     protected final Class<?> defineClass(byte[] b, int off, int len)
 767         throws ClassFormatError
 768     {
 769         return defineClass(null, b, off, len, null);
 770     }


 977         Class<?> c = defineClass1(name, b, off, len, protectionDomain, source);
 978         postDefineClass(c, protectionDomain);
 979         return c;
 980     }
 981 
 982     /**
 983      * Converts a {@link java.nio.ByteBuffer ByteBuffer} into an instance
 984      * of class {@code Class}, with the given {@code ProtectionDomain}.
 985      * If the given {@code ProtectionDomain} is {@code null}, then a default
 986      * protection domain will be assigned to the class as
 987      * specified in the documentation for {@link #defineClass(String, byte[],
 988      * int, int)}.  Before the class can be used it must be resolved.
 989      *
 990      * <p>The rules about the first class defined in a package determining the
 991      * set of certificates for the package, the restrictions on class names,
 992      * and the defined package of the class
 993      * are identical to those specified in the documentation for {@link
 994      * #defineClass(String, byte[], int, int, ProtectionDomain)}.
 995      *
 996      * <p> An invocation of this method of the form
 997      * <i>cl</i>{@code .defineClass(}<i>name</i>{@code ,}
 998      * <i>bBuffer</i>{@code ,} <i>pd</i>{@code )} yields exactly the same
 999      * result as the statements
1000      *
1001      *<p> <code>
1002      * ...<br>
1003      * byte[] temp = new byte[bBuffer.{@link
1004      * java.nio.ByteBuffer#remaining remaining}()];<br>
1005      *     bBuffer.{@link java.nio.ByteBuffer#get(byte[])
1006      * get}(temp);<br>
1007      *     return {@link #defineClass(String, byte[], int, int, ProtectionDomain)
1008      * cl.defineClass}(name, temp, 0,
1009      * temp.length, pd);<br>
1010      * </code></p>
1011      *
1012      * @param  name
1013      *         The expected <a href="#name">binary name</a>. of the class, or
1014      *         {@code null} if not known
1015      *
1016      * @param  b
1017      *         The bytes that make up the class data. The bytes from positions
1018      *         {@code b.position()} through {@code b.position() + b.limit() -1
1019      *         } should have the format of a valid class file as defined by
1020      *         <cite>The Java&trade; Virtual Machine Specification</cite>.
1021      *
1022      * @param  protectionDomain
1023      *         The {@code ProtectionDomain} of the class, or {@code null}.
1024      *
1025      * @return  The {@code Class} object created from the data,
1026      *          and {@code ProtectionDomain}.
1027      *
1028      * @throws  ClassFormatError
1029      *          If the data did not contain a valid class.
1030      *
1031      * @throws  NoClassDefFoundError
1032      *          If {@code name} is not {@code null} and not equal to the
1033      *          <a href="#name">binary name</a> of the class specified by {@code b}
1034      *
1035      * @throws  SecurityException
1036      *          If an attempt is made to add this class to a package that
1037      *          contains classes that were signed by a different set of
1038      *          certificates than this class, or if {@code name} begins with
1039      *          "{@code java.}".


1141             if (!match) return false;
1142         }
1143 
1144         // now do the same for pcerts
1145         for (Certificate pcert : pcerts) {
1146             match = false;
1147             for (Certificate cert : certs) {
1148                 if (pcert.equals(cert)) {
1149                     match = true;
1150                     break;
1151                 }
1152             }
1153             if (!match) return false;
1154         }
1155 
1156         return true;
1157     }
1158 
1159     /**
1160      * Links the specified class.  This (misleadingly named) method may be
1161      * used by a class loader to link a class.  If the class {@code c} has
1162      * already been linked, then this method simply returns. Otherwise, the
1163      * class is linked as described in the "Execution" chapter of
1164      * <cite>The Java&trade; Language Specification</cite>.
1165      *
1166      * @param  c
1167      *         The class to link
1168      *
1169      * @throws  NullPointerException
1170      *          If {@code c} is {@code null}.
1171      *
1172      * @see  #defineClass(String, byte[], int, int)
1173      */
1174     protected final void resolveClass(Class<?> c) {
1175         if (c == null) {
1176             throw new NullPointerException();
1177         }
1178     }
1179 
1180     /**
1181      * Finds a class with the specified <a href="#name">binary name</a>,
1182      * loading it if necessary.
1183      *
1184      * <p> This method loads the class through the system class loader (see
1185      * {@link #getSystemClassLoader()}).  The {@code Class} object returned
1186      * might have more than one {@code ClassLoader} associated with it.
1187      * Subclasses of {@code ClassLoader} need not usually invoke this method,
1188      * because most class loaders need to override just {@link
1189      * #findClass(String)}.  </p>
1190      *
1191      * @param  name
1192      *         The <a href="#name">binary name</a> of the class
1193      *
1194      * @return  The {@code Class} object for the specified {@code name}
1195      *
1196      * @throws  ClassNotFoundException
1197      *          If the class could not be found
1198      *
1199      * @see  #ClassLoader(ClassLoader)
1200      * @see  #getParent()
1201      */
1202     protected final Class<?> findSystemClass(String name)
1203         throws ClassNotFoundException
1204     {
1205         return getSystemClassLoader().loadClass(name);
1206     }
1207 
1208     /**
1209      * Returns a class loaded by the bootstrap class loader;
1210      * or return null if not found.
1211      */
1212     Class<?> findBootstrapClassOrNull(String name) {
1213         if (!checkName(name)) return null;
1214 
1215         return findBootstrapClass(name);
1216     }
1217 
1218     // return null if not found
1219     private native Class<?> findBootstrapClass(String name);
1220 
1221     /**
1222      * Returns the class with the given <a href="#name">binary name</a> if this
1223      * loader has been recorded by the Java virtual machine as an initiating
1224      * loader of a class with that <a href="#name">binary name</a>.  Otherwise
1225      * {@code null} is returned.
1226      *
1227      * @param  name
1228      *         The <a href="#name">binary name</a> of the class
1229      *
1230      * @return  The {@code Class} object, or {@code null} if the class has
1231      *          not been loaded
1232      *
1233      * @since  1.1
1234      */
1235     protected final Class<?> findLoadedClass(String name) {
1236         if (!checkName(name))
1237             return null;
1238         return findLoadedClass0(name);
1239     }
1240 
1241     private final native Class<?> findLoadedClass0(String name);
1242 
1243     /**
1244      * Sets the signers of a class.  This should be invoked after defining a
1245      * class.
1246      *
1247      * @param  c
1248      *         The {@code Class} object
1249      *
1250      * @param  signers
1251      *         The signers for the class
1252      *
1253      * @since  1.1
1254      */
1255     protected final void setSigners(Class<?> c, Object[] signers) {
1256         c.setSigners(signers);
1257     }
1258 
1259 
1260     // -- Resources --
1261 
1262     /**
1263      * Returns a URL to a resource in a module defined to this class loader.
1264      * Class loader implementations that support the loading from modules
1265      * should override this method.
1266      *
1267      * @apiNote This method is the basis for the {@code Class} {@link
1268      * Class#getResource getResource} and {@link Class#getResourceAsStream


1289      *
1290      * @throws IOException
1291      *         If I/O errors occur
1292      *
1293      * @see java.lang.module.ModuleReader#find(String)
1294      * @since 9
1295      */
1296     protected URL findResource(String moduleName, String name) throws IOException {
1297         if (moduleName == null) {
1298             return findResource(name);
1299         } else {
1300             return null;
1301         }
1302     }
1303 
1304     /**
1305      * Finds the resource with the given name.  A resource is some data
1306      * (images, audio, text, etc) that can be accessed by class code in a way
1307      * that is independent of the location of the code.
1308      *
1309      * <p> The name of a resource is a '{@code /}'-separated path name that
1310      * identifies the resource.
1311      *
1312      * <p> This method will first search the parent class loader for the
1313      * resource; if the parent is {@code null} the path of the class loader
1314      * built-in to the virtual machine is searched.  That failing, this method
1315      * will invoke {@link #findResource(String)} to find the resource.  </p>
1316      *
1317      * <p> Resources in named modules are subject to the encapsulation rules
1318      * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.
1319      * Additionally, and except for the special case where the resource has a
1320      * name ending with "{@code .class}", this method will only find resources in
1321      * packages of named modules when the package is {@link Module#isOpen(String)
1322      * opened} unconditionally (even if the caller of this method is in the
1323      * same module as the resource). </p>
1324      *
1325      * @apiNote Where several modules are defined to the same class loader,
1326      * and where more than one module contains a resource with the given name,
1327      * then the ordering that modules are searched is not specified and may be
1328      * very unpredictable.
1329      * When overriding this method it is recommended that an implementation
1330      * ensures that any delegation is consistent with the {@link
1331      * #getResources(java.lang.String) getResources(String)} method.
1332      *
1333      * @param  name


1345      */
1346     public URL getResource(String name) {
1347         Objects.requireNonNull(name);
1348         URL url;
1349         if (parent != null) {
1350             url = parent.getResource(name);
1351         } else {
1352             url = BootLoader.findResource(name);
1353         }
1354         if (url == null) {
1355             url = findResource(name);
1356         }
1357         return url;
1358     }
1359 
1360     /**
1361      * Finds all the resources with the given name. A resource is some data
1362      * (images, audio, text, etc) that can be accessed by class code in a way
1363      * that is independent of the location of the code.
1364      *
1365      * <p> The name of a resource is a {@code /}-separated path name that
1366      * identifies the resource.
1367      *
1368      * <p> The delegation order for searching is described in the documentation
1369      * for {@link #getResource(String)}.  </p>
1370      *
1371      * <p> Resources in named modules are subject to the encapsulation rules
1372      * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.
1373      * Additionally, and except for the special case where the resource has a
1374      * name ending with "{@code .class}", this method will only find resources in
1375      * packages of named modules when the package is {@link Module#isOpen(String)
1376      * opened} unconditionally (even if the caller of this method is in the
1377      * same module as the resource).</p>
1378      *
1379      * @apiNote Where several modules are defined to the same class loader,
1380      * and where more than one module contains a resource with the given name,
1381      * then the ordering is not specified and may be very unpredictable.
1382      * When overriding this method it is recommended that an
1383      * implementation ensures that any delegation is consistent with the {@link
1384      * #getResource(java.lang.String) getResource(String)} method. This should
1385      * ensure that the first element returned by the Enumeration's
1386      * {@code nextElement} method is the same resource that the
1387      * {@code getResource(String)} method would return.
1388      *
1389      * @param  name
1390      *         The resource name
1391      *
1392      * @return  An enumeration of {@link java.net.URL URL} objects for
1393      *          the resource. If no resources could  be found, the enumeration
1394      *          will be empty. Resources for which a {@code URL} cannot be
1395      *          constructed, are in package that is not opened unconditionally,
1396      *          or access to the resource is denied by the security manager,
1397      *          are not returned in the enumeration.
1398      *
1399      * @throws  IOException
1400      *          If I/O errors occur
1401      * @throws  NullPointerException If {@code name} is {@code null}
1402      *
1403      * @see  #findResources(String)
1404      *
1405      * @since  1.2
1406      */
1407     public Enumeration<URL> getResources(String name) throws IOException {
1408         Objects.requireNonNull(name);
1409         @SuppressWarnings("unchecked")
1410         Enumeration<URL>[] tmp = (Enumeration<URL>[]) new Enumeration<?>[2];
1411         if (parent != null) {
1412             tmp[0] = parent.getResources(name);


1488      * it must not find non-"{@code .class}" resources in packages of named
1489      * modules unless the package is {@link Module#isOpen(String) opened}
1490      * unconditionally. </p>
1491      *
1492      * @param  name
1493      *         The resource name
1494      *
1495      * @return  {@code URL} object for reading the resource; {@code null} if
1496      *          the resource could not be found, a {@code URL} could not be
1497      *          constructed to locate the resource, the resource is in a package
1498      *          that is not opened unconditionally, or access to the resource is
1499      *          denied by the security manager.
1500      *
1501      * @since  1.2
1502      */
1503     protected URL findResource(String name) {
1504         return null;
1505     }
1506 
1507     /**
1508      * Returns an enumeration of {@link java.net.URL URL} objects
1509      * representing all the resources with the given name. Class loader
1510      * implementations should override this method to specify where to load
1511      * resources from.
1512      *
1513      * <p> For resources in named modules then the method must implement the
1514      * rules for encapsulation specified in the {@code Module} {@link
1515      * Module#getResourceAsStream getResourceAsStream} method. Additionally,
1516      * it must not find non-"{@code .class}" resources in packages of named
1517      * modules unless the package is {@link Module#isOpen(String) opened}
1518      * unconditionally. </p>
1519      *
1520      * @param  name
1521      *         The resource name
1522      *
1523      * @return  An enumeration of {@link java.net.URL URL} objects for
1524      *          the resource. If no resources could  be found, the enumeration
1525      *          will be empty. Resources for which a {@code URL} cannot be
1526      *          constructed, are in a package that is not opened unconditionally,
1527      *          or access to the resource is denied by the security manager,
1528      *          are not returned in the enumeration.
1529      *
1530      * @throws  IOException
1531      *          If I/O errors occur
1532      *
1533      * @since  1.2
1534      */
1535     protected Enumeration<URL> findResources(String name) throws IOException {
1536         return Collections.emptyEnumeration();
1537     }
1538 
1539     /**
1540      * Registers the caller as
1541      * {@linkplain #isRegisteredAsParallelCapable() parallel capable}.
1542      * The registration succeeds if and only if all of the following
1543      * conditions are met:


1577      */
1578     public final boolean isRegisteredAsParallelCapable() {
1579         return ParallelLoaders.isRegistered(this.getClass());
1580     }
1581 
1582     /**
1583      * Find a resource of the specified name from the search path used to load
1584      * classes.  This method locates the resource through the system class
1585      * loader (see {@link #getSystemClassLoader()}).
1586      *
1587      * <p> Resources in named modules are subject to the encapsulation rules
1588      * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.
1589      * Additionally, and except for the special case where the resource has a
1590      * name ending with "{@code .class}", this method will only find resources in
1591      * packages of named modules when the package is {@link Module#isOpen(String)
1592      * opened} unconditionally. </p>
1593      *
1594      * @param  name
1595      *         The resource name
1596      *
1597      * @return  A {@link java.net.URL URL} to the resource; {@code
1598      *          null} if the resource could not be found, a URL could not be
1599      *          constructed to locate the resource, the resource is in a package
1600      *          that is not opened unconditionally or access to the resource is
1601      *          denied by the security manager.
1602      *
1603      * @since  1.1
1604      */
1605     public static URL getSystemResource(String name) {
1606         return getSystemClassLoader().getResource(name);
1607     }
1608 
1609     /**
1610      * Finds all resources of the specified name from the search path used to
1611      * load classes.  The resources thus found are returned as an
1612      * {@link java.util.Enumeration Enumeration} of {@link
1613      * java.net.URL URL} objects.
1614      *
1615      * <p> The search order is described in the documentation for {@link
1616      * #getSystemResource(String)}.  </p>
1617      *
1618      * <p> Resources in named modules are subject to the encapsulation rules
1619      * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.
1620      * Additionally, and except for the special case where the resource has a
1621      * name ending with "{@code .class}", this method will only find resources in
1622      * packages of named modules when the package is {@link Module#isOpen(String)
1623      * opened} unconditionally. </p>
1624      *
1625      * @param  name
1626      *         The resource name
1627      *
1628      * @return  An enumeration of {@link java.net.URL URL} objects for
1629      *          the resource. If no resources could  be found, the enumeration
1630      *          will be empty. Resources for which a {@code URL} cannot be
1631      *          constructed, are in a package that is not opened unconditionally,
1632      *          or access to the resource is denied by the security manager,
1633      *          are not returned in the enumeration.
1634      *
1635      * @throws  IOException
1636      *          If I/O errors occur
1637      *
1638      * @since  1.2
1639      */
1640     public static Enumeration<URL> getSystemResources(String name)
1641         throws IOException
1642     {
1643         return getSystemClassLoader().getResources(name);
1644     }
1645 
1646     /**
1647      * Returns an input stream for reading the specified resource.
1648      *


1697      *          resource could not be found, the resource is in a package that
1698      *          is not opened unconditionally, or access to the resource is
1699      *          denied by the security manager.
1700      *
1701      * @since  1.1
1702      */
1703     public static InputStream getSystemResourceAsStream(String name) {
1704         URL url = getSystemResource(name);
1705         try {
1706             return url != null ? url.openStream() : null;
1707         } catch (IOException e) {
1708             return null;
1709         }
1710     }
1711 
1712 
1713     // -- Hierarchy --
1714 
1715     /**
1716      * Returns the parent class loader for delegation. Some implementations may
1717      * use {@code null} to represent the bootstrap class loader. This method
1718      * will return {@code null} in such implementations if this class loader's
1719      * parent is the bootstrap class loader.
1720      *
1721      * @return  The parent {@code ClassLoader}
1722      *
1723      * @throws  SecurityException
1724      *          If a security manager is present, and the caller's class loader
1725      *          is not {@code null} and is not an ancestor of this class loader,
1726      *          and the caller does not have the
1727      *          {@link RuntimePermission}{@code ("getClassLoader")}
1728      *
1729      * @since  1.2
1730      */
1731     @CallerSensitive
1732     public final ClassLoader getParent() {
1733         if (parent == null)
1734             return null;
1735         SecurityManager sm = System.getSecurityManager();
1736         if (sm != null) {
1737             // Check access to the parent class loader
1738             // If the caller's class loader is same as this class loader,
1739             // permission check is performed.
1740             checkClassLoaderPermission(parent, Reflection.getCallerClass());
1741         }


1768      *          If a security manager is present, and the caller's class loader is
1769      *          not {@code null}, and the caller's class loader is not the same
1770      *          as or an ancestor of the platform class loader,
1771      *          and the caller does not have the
1772      *          {@link RuntimePermission}{@code ("getClassLoader")}
1773      *
1774      * @since 9
1775      */
1776     @CallerSensitive
1777     public static ClassLoader getPlatformClassLoader() {
1778         SecurityManager sm = System.getSecurityManager();
1779         ClassLoader loader = getBuiltinPlatformClassLoader();
1780         if (sm != null) {
1781             checkClassLoaderPermission(loader, Reflection.getCallerClass());
1782         }
1783         return loader;
1784     }
1785 
1786     /**
1787      * Returns the system class loader for delegation.  This is the default
1788      * delegation parent for new {@code ClassLoader} instances, and is
1789      * typically the class loader used to start the application.
1790      *
1791      * <p> This method is first invoked early in the runtime's startup
1792      * sequence, at which point it creates the system class loader. This
1793      * class loader will be the context class loader for the main application
1794      * thread (for example, the thread that invokes the {@code main} method of
1795      * the main class).
1796      *
1797      * <p> The default system class loader is an implementation-dependent
1798      * instance of this class.
1799      *
1800      * <p> If the system property "{@code java.system.class.loader}" is defined
1801      * when this method is first invoked then the value of that property is
1802      * taken to be the name of a class that will be returned as the system
1803      * class loader.  The class is loaded using the default system class loader
1804      * and must define a public constructor that takes a single parameter of
1805      * type {@code ClassLoader} which is used as the delegation parent.  An
1806      * instance is then created using this constructor with the default system
1807      * class loader as the parameter.  The resulting class loader is defined
1808      * to be the system class loader. During construction, the class loader
1809      * should take great care to avoid calling {@code getSystemClassLoader()}.
1810      * If circular initialization of the system class loader is detected then
1811      * an unspecified error or exception is thrown.
1812      *
1813      * @implNote The system property to override the system class loader is not
1814      * examined until the VM is almost fully initialized. Code that executes
1815      * this method during startup should take care not to cache the return
1816      * value until the system is fully initialized.
1817      *
1818      * <p> The name of the built-in system class loader is {@code "app"}.
1819      * The class path used by the built-in system class loader is determined
1820      * by the system property "{@code java.class.path}" during early
1821      * initialization of the VM. If the system property is not defined,
1822      * or its value is an empty string, then there is no class path
1823      * when the initial module is a module on the application module path,
1824      * i.e. <em>a named module</em>. If the initial module is not on
1825      * the application module path then the class path defaults to
1826      * the current working directory.
1827      *
1828      * @return  The system {@code ClassLoader} for delegation
1829      *
1830      * @throws  SecurityException
1831      *          If a security manager is present, and the caller's class loader
1832      *          is not {@code null} and is not the same as or an ancestor of the
1833      *          system class loader, and the caller does not have the
1834      *          {@link RuntimePermission}{@code ("getClassLoader")}
1835      *
1836      * @throws  IllegalStateException
1837      *          If invoked recursively during the construction of the class
1838      *          loader specified by the "{@code java.system.class.loader}"
1839      *          property.
1840      *
1841      * @throws  Error
1842      *          If the system property "{@code java.system.class.loader}"
1843      *          is defined but the named class could not be loaded, the
1844      *          provider class does not define the required constructor, or an
1845      *          exception is thrown by that constructor when it is invoked. The
1846      *          underlying cause of the error can be retrieved via the
1847      *          {@link Throwable#getCause()} method.
1848      *
1849      * @revised  1.4
1850      */
1851     @CallerSensitive
1852     public static ClassLoader getSystemClassLoader() {
1853         switch (VM.initLevel()) {
1854             case 0:
1855             case 1:
1856             case 2:
1857                 // the system class loader is the built-in app class loader during startup
1858                 return getBuiltinAppClassLoader();
1859             case 3:
1860                 throw new InternalError("getSystemClassLoader should only be called after VM booted");
1861             case 4:
1862                 // system fully initialized


2232                      .toArray(Package[]::new);
2233     }
2234 
2235 
2236 
2237     // package-private
2238 
2239     /**
2240      * Returns a stream of Packages defined in this class loader
2241      */
2242     Stream<Package> packages() {
2243         return packages.values().stream()
2244                        .map(p -> definePackage(p.packageName(), p.module()));
2245     }
2246 
2247     // -- Native library access --
2248 
2249     /**
2250      * Returns the absolute path name of a native library.  The VM invokes this
2251      * method to locate the native libraries that belong to classes loaded with
2252      * this class loader. If this method returns {@code null}, the VM
2253      * searches the library along the path specified as the
2254      * "{@code java.library.path}" property.
2255      *
2256      * @param  libname
2257      *         The library name
2258      *
2259      * @return  The absolute path of the native library
2260      *
2261      * @see  System#loadLibrary(String)
2262      * @see  System#mapLibraryName(String)
2263      *
2264      * @since  1.2
2265      */
2266     protected String findLibrary(String libname) {
2267         return null;
2268     }
2269 
2270     /**
2271      * The inner class NativeLibrary denotes a loaded native library instance.
2272      * Every classloader contains a vector of loaded native libraries in the
2273      * private field {@code nativeLibraries}.  The native libraries loaded
2274      * into the system are entered into the {@code systemNativeLibraries}
2275      * vector.
2276      *
2277      * <p> Every native library requires a particular version of JNI. This is
2278      * denoted by the private {@code jniVersion} field.  This field is set by
2279      * the VM when it loads the library, and used by the VM to pass the correct
2280      * version of JNI to the native methods.  </p>
2281      *
2282      * @see      ClassLoader
2283      * @since    1.2
2284      */
2285     static class NativeLibrary {
2286         // opaque handle to native library, used in native code.
2287         long handle;
2288         // the version of JNI environment the native library requires.
2289         private int jniVersion;
2290         // the class from which the library is loaded, also indicates
2291         // the loader this native library belongs.
2292         private final Class<?> fromClass;
2293         // the canonicalized name of the native library.
2294         // or static library name
2295         String name;
2296         // Indicates if the native library is linked into the VM
2297         boolean isBuiltin;
2298         // Indicates if the native library is loaded


2575     // been invoked.
2576     // @GuardedBy("assertionLock")
2577     private Map<String, Boolean> packageAssertionStatus = null;
2578 
2579     // Maps String fullyQualifiedClassName to Boolean assertionStatus If this
2580     // field is null then we are delegating assertion status queries to the VM,
2581     // i.e., none of this ClassLoader's assertion status modification methods
2582     // have been invoked.
2583     // @GuardedBy("assertionLock")
2584     Map<String, Boolean> classAssertionStatus = null;
2585 
2586     /**
2587      * Sets the default assertion status for this class loader.  This setting
2588      * determines whether classes loaded by this class loader and initialized
2589      * in the future will have assertions enabled or disabled by default.
2590      * This setting may be overridden on a per-package or per-class basis by
2591      * invoking {@link #setPackageAssertionStatus(String, boolean)} or {@link
2592      * #setClassAssertionStatus(String, boolean)}.
2593      *
2594      * @param  enabled
2595      *         {@code true} if classes loaded by this class loader will
2596      *         henceforth have assertions enabled by default, {@code false}
2597      *         if they will have assertions disabled by default.
2598      *
2599      * @since  1.4
2600      */
2601     public void setDefaultAssertionStatus(boolean enabled) {
2602         synchronized (assertionLock) {
2603             if (classAssertionStatus == null)
2604                 initializeJavaAssertionMaps();
2605 
2606             defaultAssertionStatus = enabled;
2607         }
2608     }
2609 
2610     /**
2611      * Sets the package default assertion status for the named package.  The
2612      * package default assertion status determines the assertion status for
2613      * classes initialized in the future that belong to the named package or
2614      * any of its "subpackages".
2615      *
2616      * <p> A subpackage of a package named p is any package whose name begins
2617      * with "{@code p.}".  For example, {@code javax.swing.text} is a
2618      * subpackage of {@code javax.swing}, and both {@code java.util} and
2619      * {@code java.lang.reflect} are subpackages of {@code java}.
2620      *
2621      * <p> In the event that multiple package defaults apply to a given class,
2622      * the package default pertaining to the most specific package takes
2623      * precedence over the others.  For example, if {@code javax.lang} and
2624      * {@code javax.lang.reflect} both have package defaults associated with
2625      * them, the latter package default applies to classes in
2626      * {@code javax.lang.reflect}.
2627      *
2628      * <p> Package defaults take precedence over the class loader's default
2629      * assertion status, and may be overridden on a per-class basis by invoking
2630      * {@link #setClassAssertionStatus(String, boolean)}.  </p>
2631      *
2632      * @param  packageName
2633      *         The name of the package whose package default assertion status
2634      *         is to be set. A {@code null} value indicates the unnamed
2635      *         package that is "current"
2636      *         (see section 7.4.2 of
2637      *         <cite>The Java&trade; Language Specification</cite>.)
2638      *
2639      * @param  enabled
2640      *         {@code true} if classes loaded by this classloader and
2641      *         belonging to the named package or any of its subpackages will
2642      *         have assertions enabled by default, {@code false} if they will
2643      *         have assertions disabled by default.
2644      *
2645      * @since  1.4
2646      */
2647     public void setPackageAssertionStatus(String packageName,
2648                                           boolean enabled) {
2649         synchronized (assertionLock) {
2650             if (packageAssertionStatus == null)
2651                 initializeJavaAssertionMaps();
2652 
2653             packageAssertionStatus.put(packageName, enabled);
2654         }
2655     }
2656 
2657     /**
2658      * Sets the desired assertion status for the named top-level class in this
2659      * class loader and any nested classes contained therein.  This setting
2660      * takes precedence over the class loader's default assertion status, and
2661      * over any applicable per-package default.  This method has no effect if
2662      * the named class has already been initialized.  (Once a class is
2663      * initialized, its assertion status cannot change.)
2664      *
2665      * <p> If the named class is not a top-level class, this invocation will
2666      * have no effect on the actual assertion status of any class. </p>
2667      *
2668      * @param  className
2669      *         The fully qualified class name of the top-level class whose
2670      *         assertion status is to be set.
2671      *
2672      * @param  enabled
2673      *         {@code true} if the named class is to have assertions
2674      *         enabled when (and if) it is initialized, {@code false} if the
2675      *         class is to have assertions disabled.
2676      *
2677      * @since  1.4
2678      */
2679     public void setClassAssertionStatus(String className, boolean enabled) {
2680         synchronized (assertionLock) {
2681             if (classAssertionStatus == null)
2682                 initializeJavaAssertionMaps();
2683 
2684             classAssertionStatus.put(className, enabled);
2685         }
2686     }
2687 
2688     /**
2689      * Sets the default assertion status for this class loader to
2690      * {@code false} and discards any package defaults or class assertion
2691      * status settings associated with the class loader.  This method is
2692      * provided so that class loaders can be made to ignore any command line or
2693      * persistent assertion status settings and "start with a clean slate."
2694      *
2695      * @since  1.4
2696      */
2697     public void clearAssertionStatus() {
2698         /*
2699          * Whether or not "Java assertion maps" are initialized, set
2700          * them to empty maps, effectively ignoring any present settings.
2701          */
2702         synchronized (assertionLock) {
2703             classAssertionStatus = new HashMap<>();
2704             packageAssertionStatus = new HashMap<>();
2705             defaultAssertionStatus = false;
2706         }
2707     }
2708 
2709     /**
2710      * Returns the assertion status that would be assigned to the specified


< prev index next >