< prev index next >

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

Print this page




 190  * {@code ClassLoader} must be a binary name as defined by
 191  * <cite>The Java&trade; Language Specification</cite>.
 192  *
 193  * <p> Examples of valid class names include:
 194  * <blockquote><pre>
 195  *   "java.lang.String"
 196  *   "javax.swing.JSpinner$DefaultEditor"
 197  *   "java.security.KeyStore$Builder$FileBuilder$1"
 198  *   "java.net.URLClassLoader$3$1"
 199  * </pre></blockquote>
 200  *
 201  * <p> Any package name provided as a {@code String} parameter to methods in
 202  * {@code ClassLoader} must be either the empty string (denoting an unnamed package)
 203  * or a fully qualified name as defined by
 204  * <cite>The Java&trade; Language Specification</cite>.
 205  *
 206  * @jls 6.7  Fully Qualified Names
 207  * @jls 13.1 The Form of a Binary
 208  * @see      #resolveClass(Class)
 209  * @since 1.0


 210  */
 211 public abstract class ClassLoader {
 212 
 213     private static native void registerNatives();
 214     static {
 215         registerNatives();
 216     }
 217 
 218     // The parent class loader for delegation
 219     // Note: VM hardcoded the offset of this field, thus all new fields
 220     // must be added *after* it.
 221     private final ClassLoader parent;
 222 
 223     // class loader name
 224     private final String name;
 225 
 226     // the unnamed module for this ClassLoader
 227     private final Module unnamedModule;
 228 
 229     /**


 363             package2certs = new Hashtable<>();
 364             assertionLock = this;
 365         }
 366     }
 367 
 368     /**
 369      * Creates a new class loader of the specified name and using the
 370      * specified parent class loader for delegation.
 371      *
 372      * @param  name   class loader name; or {@code null} if not named
 373      * @param  parent the parent class loader
 374      *
 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) {


 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)}.


 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
 698      * invoking {@link #findClass(String)} when the {@code moduleName} is
 699      * {@code null}. It otherwise returns {@code null}.
 700      *
 701      * @param  moduleName
 702      *         The module name; or {@code null} to find the class in the
 703      *         {@linkplain #getUnnamedModule() unnamed module} for this
 704      *         class loader
 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


 817      *
 818      * @throws  ClassFormatError
 819      *          If the data did not contain a valid class
 820      *
 821      * @throws  IndexOutOfBoundsException
 822      *          If either {@code off} or {@code len} is negative, or if
 823      *          {@code off+len} is greater than {@code b.length}.
 824      *
 825      * @throws  SecurityException
 826      *          If an attempt is made to add this class to a package that
 827      *          contains classes that were signed by a different set of
 828      *          certificates than this class (which is unsigned), or if
 829      *          {@code name} begins with "{@code java.}".
 830      *
 831      * @see  #loadClass(String, boolean)
 832      * @see  #resolveClass(Class)
 833      * @see  java.security.CodeSource
 834      * @see  java.security.SecureClassLoader
 835      *
 836      * @since  1.1


 837      */
 838     protected final Class<?> defineClass(String name, byte[] b, int off, int len)
 839         throws ClassFormatError
 840     {
 841         return defineClass(name, b, off, len, null);
 842     }
 843 
 844     /* Determine protection domain, and check that:
 845         - not define java.* class,
 846         - signer of this class matches signers for the rest of the classes in
 847           package.
 848     */
 849     private ProtectionDomain preDefineClass(String name,
 850                                             ProtectionDomain pd)
 851     {
 852         if (!checkName(name))
 853             throw new NoClassDefFoundError("IllegalName: " + name);
 854 
 855         // Note:  Checking logic in java.lang.invoke.MemberName.checkForTypeAlias
 856         // relies on the fact that spoofing is impossible if a class has a name


 950      * @return  The {@code Class} object created from the data,
 951      *          and {@code ProtectionDomain}.
 952      *
 953      * @throws  ClassFormatError
 954      *          If the data did not contain a valid class
 955      *
 956      * @throws  NoClassDefFoundError
 957      *          If {@code name} is not {@code null} and not equal to the
 958      *          <a href="#name">binary name</a> of the class specified by {@code b}
 959      *
 960      * @throws  IndexOutOfBoundsException
 961      *          If either {@code off} or {@code len} is negative, or if
 962      *          {@code off+len} is greater than {@code b.length}.
 963      *
 964      * @throws  SecurityException
 965      *          If an attempt is made to add this class to a package that
 966      *          contains classes that were signed by a different set of
 967      *          certificates than this class, or if {@code name} begins with
 968      *          "{@code java.}" and this class loader is not the platform
 969      *          class loader or its ancestor.



 970      */
 971     protected final Class<?> defineClass(String name, byte[] b, int off, int len,
 972                                          ProtectionDomain protectionDomain)
 973         throws ClassFormatError
 974     {
 975         protectionDomain = preDefineClass(name, protectionDomain);
 976         String source = defineClassSourceLocation(protectionDomain);
 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      *


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.}".
1040      *
1041      * @see      #defineClass(String, byte[], int, int, ProtectionDomain)
1042      *
1043      * @since  1.5


1044      */
1045     protected final Class<?> defineClass(String name, java.nio.ByteBuffer b,
1046                                          ProtectionDomain protectionDomain)
1047         throws ClassFormatError
1048     {
1049         int len = b.remaining();
1050 
1051         // Use byte[] if not a direct ByteBuffer:
1052         if (!b.isDirect()) {
1053             if (b.hasArray()) {
1054                 return defineClass(name, b.array(),
1055                                    b.position() + b.arrayOffset(), len,
1056                                    protectionDomain);
1057             } else {
1058                 // no array, or read-only array
1059                 byte[] tb = new byte[len];
1060                 b.get(tb);  // get bytes out of byte buffer.
1061                 return defineClass(name, tb, 0, len, protectionDomain);
1062             }
1063         }


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
1269      * getResourceAsStream} methods. It is not subject to the rules for
1270      * encapsulation specified by {@code Module} {@link
1271      * Module#getResourceAsStream getResourceAsStream}.
1272      *
1273      * @implSpec The default implementation attempts to find the resource by
1274      * invoking {@link #findResource(String)} when the {@code moduleName} is
1275      * {@code null}. It otherwise returns {@code null}.
1276      *
1277      * @param  moduleName
1278      *         The module name; or {@code null} to find a resource in the
1279      *         {@linkplain #getUnnamedModule() unnamed module} for this
1280      *         class loader
1281      * @param  name
1282      *         The resource name
1283      *
1284      * @return A URL to the resource; {@code null} if the resource could not be
1285      *         found, a URL could not be constructed to locate the resource,
1286      *         access to the resource is denied by the security manager, or
1287      *         there isn't a module of the given name defined to the class
1288      *         loader.
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


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
1334      *         The resource name
1335      *
1336      * @return  {@code URL} object for reading the resource; {@code null} if
1337      *          the resource could not be found, a {@code URL} could not be
1338      *          constructed to locate the resource, the resource is in a package
1339      *          that is not opened unconditionally, or access to the resource is
1340      *          denied by the security manager.
1341      *
1342      * @throws  NullPointerException If {@code name} is {@code null}
1343      *
1344      * @since  1.1


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      *


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);
1413         } else {
1414             tmp[0] = BootLoader.findResources(name);
1415         }
1416         tmp[1] = findResources(name);
1417 
1418         return new CompoundEnumeration<>(tmp);
1419     }
1420 
1421     /**
1422      * Returns a stream whose elements are the URLs of all the resources with
1423      * the given name. A resource is some data (images, audio, text, etc) that
1424      * can be accessed by class code in a way that is independent of the
1425      * location of the code.


1482      * Finds the resource with the given name. Class loader implementations
1483      * should override this method to specify where to find resources.
1484      *
1485      * <p> For resources in named modules then the method must implement the
1486      * rules for encapsulation specified in the {@code Module} {@link
1487      * Module#getResourceAsStream getResourceAsStream} method. Additionally,
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:
1544      * <ol>
1545      * <li> no instance of the caller has been created</li>
1546      * <li> all of the super classes (except class Object) of the caller are
1547      * registered as parallel capable</li>
1548      * </ol>
1549      * <p>Note that once a class loader is registered as parallel capable, there
1550      * is no way to change it back.</p>
1551      *
1552      * @return  {@code true} if the caller is successfully registered as
1553      *          parallel capable and {@code false} if otherwise.


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      *
1649      * <p> The search order is described in the documentation for {@link
1650      * #getResource(String)}.  </p>
1651      *
1652      * <p> Resources in named modules are subject to the encapsulation rules
1653      * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.
1654      * Additionally, and except for the special case where the resource has a
1655      * name ending with "{@code .class}", this method will only find resources in
1656      * packages of named modules when the package is {@link Module#isOpen(String)
1657      * opened} unconditionally. </p>
1658      *
1659      * @param  name
1660      *         The resource name
1661      *
1662      * @return  An input stream for reading the resource; {@code null} if the
1663      *          resource could not be found, the resource is in a package that
1664      *          is not opened unconditionally, or access to the resource is
1665      *          denied by the security manager.
1666      *
1667      * @throws  NullPointerException If {@code name} is {@code null}
1668      *
1669      * @since  1.1


1670      */
1671     public InputStream getResourceAsStream(String name) {
1672         Objects.requireNonNull(name);
1673         URL url = getResource(name);
1674         try {
1675             return url != null ? url.openStream() : null;
1676         } catch (IOException e) {
1677             return null;
1678         }
1679     }
1680 
1681     /**
1682      * Open for reading, a resource of the specified name from the search path
1683      * used to load classes.  This method locates the resource through the
1684      * system class loader (see {@link #getSystemClassLoader()}).
1685      *
1686      * <p> Resources in named modules are subject to the encapsulation rules
1687      * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.
1688      * Additionally, and except for the special case where the resource has a
1689      * name ending with "{@code .class}", this method will only find resources in
1690      * packages of named modules when the package is {@link Module#isOpen(String)
1691      * opened} unconditionally. </p>
1692      *
1693      * @param  name
1694      *         The resource name
1695      *
1696      * @return  An input stream for reading the resource; {@code null} if the
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}


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         }
1742         return parent;
1743     }
1744 
1745     /**
1746      * Returns the unnamed {@code Module} for this class loader.
1747      *
1748      * @return The unnamed Module for this class loader
1749      *
1750      * @see Module#isNamed()
1751      * @since 9

1752      */
1753     public final Module getUnnamedModule() {
1754         return unnamedModule;
1755     }
1756 
1757     /**
1758      * Returns the platform class loader for delegation.  All
1759      * <a href="#builtinLoaders">platform classes</a> are visible to
1760      * the platform class loader.
1761      *
1762      * @implNote The name of the builtin platform class loader is
1763      * {@code "platform"}.
1764      *
1765      * @return  The platform {@code ClassLoader}.
1766      *
1767      * @throws  SecurityException
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


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
1863                 assert VM.isBooted() && scl != null;
1864                 SecurityManager sm = System.getSecurityManager();
1865                 if (sm != null) {
1866                     checkClassLoaderPermission(scl, Reflection.getCallerClass());
1867                 }
1868                 return scl;
1869             default:


2084      *         The implementation version
2085      *
2086      * @param  implVendor
2087      *         The implementation vendor
2088      *
2089      * @param  sealBase
2090      *         If not {@code null}, then this package is sealed with
2091      *         respect to the given code source {@link java.net.URL URL}
2092      *         object.  Otherwise, the package is not sealed.
2093      *
2094      * @return  The newly defined {@code Package} object
2095      *
2096      * @throws  NullPointerException
2097      *          if {@code name} is {@code null}.
2098      *
2099      * @throws  IllegalArgumentException
2100      *          if a package of the given {@code name} is already
2101      *          defined by this class loader
2102      *
2103      * @since  1.2


2104      *
2105      * @see <a href="../../../technotes/guides/jar/jar.html#versioning">
2106      *      The JAR File Specification: Package Versioning</a>
2107      * @see <a href="../../../technotes/guides/jar/jar.html#sealing">
2108      *      The JAR File Specification: Package Sealing</a>
2109      */
2110     protected Package definePackage(String name, String specTitle,
2111                                     String specVersion, String specVendor,
2112                                     String implTitle, String implVersion,
2113                                     String implVendor, URL sealBase)
2114     {
2115         Objects.requireNonNull(name);
2116 
2117         // definePackage is not final and may be overridden by custom class loader
2118         Package p = new Package(name, specTitle, specVersion, specVendor,
2119                                 implTitle, implVersion, implVendor,
2120                                 sealBase, this);
2121 
2122         if (packages.putIfAbsent(name, p) != null)
2123             throw new IllegalArgumentException(name);
2124 
2125         return p;
2126     }
2127 
2128     /**
2129      * Returns a {@code Package} of the given <a href="#name">name</a> that has been
2130      * defined by this class loader.
2131      *
2132      * @param  name The <a href="#name">package name</a>
2133      *
2134      * @return The {@code Package} of the given name defined by this class loader,
2135      *         or {@code null} if not found
2136      *
2137      * @throws  NullPointerException
2138      *          if {@code name} is {@code null}.
2139      *
2140      * @since  9

2141      */
2142     public final Package getDefinedPackage(String name) {
2143         Objects.requireNonNull(name, "name cannot be null");
2144 
2145         NamedPackage p = packages.get(name);
2146         if (p == null)
2147             return null;
2148 
2149         return definePackage(name, p.module());
2150     }
2151 
2152     /**
2153      * Returns all of the {@code Package}s defined by this class loader.
2154      * The returned array has no duplicated {@code Package}s of the same name.
2155      *
2156      * @apiNote This method returns an array rather than a {@code Set} or {@code Stream}
2157      *          for consistency with the existing {@link #getPackages} method.
2158      *
2159      * @return The array of {@code Package} objects defined by this class loader;
2160      *         or an zero length array if no package has been defined by this class loader.
2161      *
2162      * @since  9

2163      */
2164     public final Package[] getDefinedPackages() {
2165         return packages().toArray(Package[]::new);
2166     }
2167 
2168     /**
2169      * Finds a package by <a href="#name">name</a> in this class loader and its ancestors.
2170      * <p>
2171      * If this class loader defines a {@code Package} of the given name,
2172      * the {@code Package} is returned. Otherwise, the ancestors of
2173      * this class loader are searched recursively (parent by parent)
2174      * for a {@code Package} of the given name.
2175      *
2176      * @param  name
2177      *         The <a href="#name">package name</a>
2178      *
2179      * @return The {@code Package} corresponding to the given name defined by
2180      *         this class loader or its ancestors, or {@code null} if not found.
2181      *
2182      * @throws  NullPointerException
2183      *          if {@code name} is {@code null}.
2184      *
2185      * @deprecated
2186      * If multiple class loaders delegate to each other and define classes
2187      * with the same package name, and one such loader relies on the lookup
2188      * behavior of {@code getPackage} to return a {@code Package} from
2189      * a parent loader, then the properties exposed by the {@code Package}
2190      * may not be as expected in the rest of the program.
2191      * For example, the {@code Package} will only expose annotations from the
2192      * {@code package-info.class} file defined by the parent loader, even if
2193      * annotations exist in a {@code package-info.class} file defined by
2194      * a child loader.  A more robust approach is to use the
2195      * {@link ClassLoader#getDefinedPackage} method which returns
2196      * a {@code Package} for the specified class loader.
2197      *
2198      * @since  1.2


2199      */
2200     @Deprecated(since="9")
2201     protected Package getPackage(String name) {
2202         Package pkg = getDefinedPackage(name);
2203         if (pkg == null) {
2204             if (parent != null) {
2205                 pkg = parent.getPackage(name);
2206             } else {
2207                 pkg = BootLoader.getDefinedPackage(name);
2208             }
2209         }
2210         return pkg;
2211     }
2212 
2213     /**
2214      * Returns all of the {@code Package}s defined by this class loader
2215      * and its ancestors.  The returned array may contain more than one
2216      * {@code Package} object of the same package name, each defined by
2217      * a different class loader in the class loader hierarchy.
2218      *
2219      * @return  The array of {@code Package} objects defined by this
2220      *          class loader and its ancestors
2221      *
2222      * @since  1.2


2223      */
2224     protected Package[] getPackages() {
2225         Stream<Package> pkgs = packages();
2226         ClassLoader ld = parent;
2227         while (ld != null) {
2228             pkgs = Stream.concat(ld.packages(), pkgs);
2229             ld = ld.parent;
2230         }
2231         return Stream.concat(BootLoader.packages(), pkgs)
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() {




 190  * {@code ClassLoader} must be a binary name as defined by
 191  * <cite>The Java&trade; Language Specification</cite>.
 192  *
 193  * <p> Examples of valid class names include:
 194  * <blockquote><pre>
 195  *   "java.lang.String"
 196  *   "javax.swing.JSpinner$DefaultEditor"
 197  *   "java.security.KeyStore$Builder$FileBuilder$1"
 198  *   "java.net.URLClassLoader$3$1"
 199  * </pre></blockquote>
 200  *
 201  * <p> Any package name provided as a {@code String} parameter to methods in
 202  * {@code ClassLoader} must be either the empty string (denoting an unnamed package)
 203  * or a fully qualified name as defined by
 204  * <cite>The Java&trade; Language Specification</cite>.
 205  *
 206  * @jls 6.7  Fully Qualified Names
 207  * @jls 13.1 The Form of a Binary
 208  * @see      #resolveClass(Class)
 209  * @since 1.0
 210  * @revised 9
 211  * @spec JPMS
 212  */
 213 public abstract class ClassLoader {
 214 
 215     private static native void registerNatives();
 216     static {
 217         registerNatives();
 218     }
 219 
 220     // The parent class loader for delegation
 221     // Note: VM hardcoded the offset of this field, thus all new fields
 222     // must be added *after* it.
 223     private final ClassLoader parent;
 224 
 225     // class loader name
 226     private final String name;
 227 
 228     // the unnamed module for this ClassLoader
 229     private final Module unnamedModule;
 230 
 231     /**


 365             package2certs = new Hashtable<>();
 366             assertionLock = this;
 367         }
 368     }
 369 
 370     /**
 371      * Creates a new class loader of the specified name and using the
 372      * specified parent class loader for delegation.
 373      *
 374      * @param  name   class loader name; or {@code null} if not named
 375      * @param  parent the parent class loader
 376      *
 377      * @throws IllegalArgumentException if the given name is empty.
 378      *
 379      * @throws SecurityException
 380      *         If a security manager exists and its
 381      *         {@link SecurityManager#checkCreateClassLoader()}
 382      *         method doesn't allow creation of a new class loader.
 383      *
 384      * @since  9
 385      * @spec JPMS
 386      */
 387     protected ClassLoader(String name, ClassLoader parent) {
 388         this(checkCreateClassLoader(name), name, parent);
 389     }
 390 

 391     /**
 392      * Creates a new class loader using the specified parent class loader for
 393      * delegation.
 394      *
 395      * <p> If there is a security manager, its {@link
 396      * SecurityManager#checkCreateClassLoader()
 397      * checkCreateClassLoader} method is invoked.  This may result in
 398      * a security exception.  </p>
 399      *
 400      * @param  parent
 401      *         The parent class loader
 402      *
 403      * @throws  SecurityException
 404      *          If a security manager exists and its
 405      *          {@code checkCreateClassLoader} method doesn't allow creation
 406      *          of a new class loader.
 407      *
 408      * @since  1.2
 409      */
 410     protected ClassLoader(ClassLoader parent) {


 425      *          If a security manager exists and its
 426      *          {@code checkCreateClassLoader} method doesn't allow creation
 427      *          of a new class loader.
 428      */
 429     protected ClassLoader() {
 430         this(checkCreateClassLoader(), null, getSystemClassLoader());
 431     }
 432 
 433     /**
 434      * Returns the name of this class loader or {@code null} if
 435      * this class loader is not named.
 436      *
 437      * @apiNote This method is non-final for compatibility.  If this
 438      * method is overridden, this method must return the same name
 439      * as specified when this class loader was instantiated.
 440      *
 441      * @return name of this class loader; or {@code null} if
 442      * this class loader is not named.
 443      *
 444      * @since 9
 445      * @spec JPMS
 446      */
 447     public String getName() {
 448         return name;
 449     }
 450 
 451     // package-private used by StackTraceElement to avoid
 452     // calling the overrideable getName method
 453     final String name() {
 454         return name;
 455     }
 456 
 457     // -- Class --
 458 
 459     /**
 460      * Loads the class with the specified <a href="#name">binary name</a>.
 461      * This method searches for classes in the same manner as the {@link
 462      * #loadClass(String, boolean)} method.  It is invoked by the Java virtual
 463      * machine to resolve class references.  Invoking this method is equivalent
 464      * to invoking {@link #loadClass(String, boolean) loadClass(name,
 465      * false)}.


 696      *
 697      * @apiNote This method returns {@code null} rather than throwing
 698      *          {@code ClassNotFoundException} if the class could not be found.
 699      *
 700      * @implSpec The default implementation attempts to find the class by
 701      * invoking {@link #findClass(String)} when the {@code moduleName} is
 702      * {@code null}. It otherwise returns {@code null}.
 703      *
 704      * @param  moduleName
 705      *         The module name; or {@code null} to find the class in the
 706      *         {@linkplain #getUnnamedModule() unnamed module} for this
 707      *         class loader
 708 
 709      * @param  name
 710      *         The <a href="#name">binary name</a> of the class
 711      *
 712      * @return The resulting {@code Class} object, or {@code null}
 713      *         if the class could not be found.
 714      *
 715      * @since 9
 716      * @spec JPMS
 717      */
 718     protected Class<?> findClass(String moduleName, String name) {
 719         if (moduleName == null) {
 720             try {
 721                 return findClass(name);
 722             } catch (ClassNotFoundException ignore) { }
 723         }
 724         return null;
 725     }
 726 
 727 
 728     /**
 729      * Converts an array of bytes into an instance of class {@code Class}.
 730      * Before the {@code Class} can be used it must be resolved.  This method
 731      * is deprecated in favor of the version that takes a <a
 732      * href="#name">binary name</a> as its first argument, and is more secure.
 733      *
 734      * @param  b
 735      *         The bytes that make up the class data.  The bytes in positions
 736      *         {@code off} through {@code off+len-1} should have the format


 821      *
 822      * @throws  ClassFormatError
 823      *          If the data did not contain a valid class
 824      *
 825      * @throws  IndexOutOfBoundsException
 826      *          If either {@code off} or {@code len} is negative, or if
 827      *          {@code off+len} is greater than {@code b.length}.
 828      *
 829      * @throws  SecurityException
 830      *          If an attempt is made to add this class to a package that
 831      *          contains classes that were signed by a different set of
 832      *          certificates than this class (which is unsigned), or if
 833      *          {@code name} begins with "{@code java.}".
 834      *
 835      * @see  #loadClass(String, boolean)
 836      * @see  #resolveClass(Class)
 837      * @see  java.security.CodeSource
 838      * @see  java.security.SecureClassLoader
 839      *
 840      * @since  1.1
 841      * @revised 9
 842      * @spec JPMS
 843      */
 844     protected final Class<?> defineClass(String name, byte[] b, int off, int len)
 845         throws ClassFormatError
 846     {
 847         return defineClass(name, b, off, len, null);
 848     }
 849 
 850     /* Determine protection domain, and check that:
 851         - not define java.* class,
 852         - signer of this class matches signers for the rest of the classes in
 853           package.
 854     */
 855     private ProtectionDomain preDefineClass(String name,
 856                                             ProtectionDomain pd)
 857     {
 858         if (!checkName(name))
 859             throw new NoClassDefFoundError("IllegalName: " + name);
 860 
 861         // Note:  Checking logic in java.lang.invoke.MemberName.checkForTypeAlias
 862         // relies on the fact that spoofing is impossible if a class has a name


 956      * @return  The {@code Class} object created from the data,
 957      *          and {@code ProtectionDomain}.
 958      *
 959      * @throws  ClassFormatError
 960      *          If the data did not contain a valid class
 961      *
 962      * @throws  NoClassDefFoundError
 963      *          If {@code name} is not {@code null} and not equal to the
 964      *          <a href="#name">binary name</a> of the class specified by {@code b}
 965      *
 966      * @throws  IndexOutOfBoundsException
 967      *          If either {@code off} or {@code len} is negative, or if
 968      *          {@code off+len} is greater than {@code b.length}.
 969      *
 970      * @throws  SecurityException
 971      *          If an attempt is made to add this class to a package that
 972      *          contains classes that were signed by a different set of
 973      *          certificates than this class, or if {@code name} begins with
 974      *          "{@code java.}" and this class loader is not the platform
 975      *          class loader or its ancestor.
 976      *
 977      * @revised 9
 978      * @spec JPMS
 979      */
 980     protected final Class<?> defineClass(String name, byte[] b, int off, int len,
 981                                          ProtectionDomain protectionDomain)
 982         throws ClassFormatError
 983     {
 984         protectionDomain = preDefineClass(name, protectionDomain);
 985         String source = defineClassSourceLocation(protectionDomain);
 986         Class<?> c = defineClass1(name, b, off, len, protectionDomain, source);
 987         postDefineClass(c, protectionDomain);
 988         return c;
 989     }
 990 
 991     /**
 992      * Converts a {@link java.nio.ByteBuffer ByteBuffer} into an instance
 993      * of class {@code Class}, with the given {@code ProtectionDomain}.
 994      * If the given {@code ProtectionDomain} is {@code null}, then a default
 995      * protection domain will be assigned to the class as
 996      * specified in the documentation for {@link #defineClass(String, byte[],
 997      * int, int)}.  Before the class can be used it must be resolved.
 998      *


1033      *
1034      * @return  The {@code Class} object created from the data,
1035      *          and {@code ProtectionDomain}.
1036      *
1037      * @throws  ClassFormatError
1038      *          If the data did not contain a valid class.
1039      *
1040      * @throws  NoClassDefFoundError
1041      *          If {@code name} is not {@code null} and not equal to the
1042      *          <a href="#name">binary name</a> of the class specified by {@code b}
1043      *
1044      * @throws  SecurityException
1045      *          If an attempt is made to add this class to a package that
1046      *          contains classes that were signed by a different set of
1047      *          certificates than this class, or if {@code name} begins with
1048      *          "{@code java.}".
1049      *
1050      * @see      #defineClass(String, byte[], int, int, ProtectionDomain)
1051      *
1052      * @since  1.5
1053      * @revised 9
1054      * @spec JPMS
1055      */
1056     protected final Class<?> defineClass(String name, java.nio.ByteBuffer b,
1057                                          ProtectionDomain protectionDomain)
1058         throws ClassFormatError
1059     {
1060         int len = b.remaining();
1061 
1062         // Use byte[] if not a direct ByteBuffer:
1063         if (!b.isDirect()) {
1064             if (b.hasArray()) {
1065                 return defineClass(name, b.array(),
1066                                    b.position() + b.arrayOffset(), len,
1067                                    protectionDomain);
1068             } else {
1069                 // no array, or read-only array
1070                 byte[] tb = new byte[len];
1071                 b.get(tb);  // get bytes out of byte buffer.
1072                 return defineClass(name, tb, 0, len, protectionDomain);
1073             }
1074         }


1258      * @param  c
1259      *         The {@code Class} object
1260      *
1261      * @param  signers
1262      *         The signers for the class
1263      *
1264      * @since  1.1
1265      */
1266     protected final void setSigners(Class<?> c, Object[] signers) {
1267         c.setSigners(signers);
1268     }
1269 
1270 
1271     // -- Resources --
1272 
1273     /**
1274      * Returns a URL to a resource in a module defined to this class loader.
1275      * Class loader implementations that support the loading from modules
1276      * should override this method.
1277      *
1278      * @apiNote This method is the basis for the {@link
1279      * Class#getResource Class.getResource}, {@link Class#getResourceAsStream
1280      * Class.getResourceAsStream}, and {@link Module#getResourceAsStream
1281      * Module.getResourceAsStream} methods. It is not subject to the rules for
1282      * encapsulation specified by {@code Module.getResourceAsStream}.
1283      *
1284      * @implSpec The default implementation attempts to find the resource by
1285      * invoking {@link #findResource(String)} when the {@code moduleName} is
1286      * {@code null}. It otherwise returns {@code null}.
1287      *
1288      * @param  moduleName
1289      *         The module name; or {@code null} to find a resource in the
1290      *         {@linkplain #getUnnamedModule() unnamed module} for this
1291      *         class loader
1292      * @param  name
1293      *         The resource name
1294      *
1295      * @return A URL to the resource; {@code null} if the resource could not be
1296      *         found, a URL could not be constructed to locate the resource,
1297      *         access to the resource is denied by the security manager, or
1298      *         there isn't a module of the given name defined to the class
1299      *         loader.
1300      *
1301      * @throws IOException
1302      *         If I/O errors occur
1303      *
1304      * @see java.lang.module.ModuleReader#find(String)
1305      * @since 9
1306      * @spec JPMS
1307      */
1308     protected URL findResource(String moduleName, String name) throws IOException {
1309         if (moduleName == null) {
1310             return findResource(name);
1311         } else {
1312             return null;
1313         }
1314     }
1315 
1316     /**
1317      * Finds the resource with the given name.  A resource is some data
1318      * (images, audio, text, etc) that can be accessed by class code in a way
1319      * that is independent of the location of the code.
1320      *
1321      * <p> The name of a resource is a '{@code /}'-separated path name that
1322      * identifies the resource.
1323      *
1324      * <p> This method will first search the parent class loader for the
1325      * resource; if the parent is {@code null} the path of the class loader
1326      * built-in to the virtual machine is searched.  That failing, this method


1337      * @apiNote Where several modules are defined to the same class loader,
1338      * and where more than one module contains a resource with the given name,
1339      * then the ordering that modules are searched is not specified and may be
1340      * very unpredictable.
1341      * When overriding this method it is recommended that an implementation
1342      * ensures that any delegation is consistent with the {@link
1343      * #getResources(java.lang.String) getResources(String)} method.
1344      *
1345      * @param  name
1346      *         The resource name
1347      *
1348      * @return  {@code URL} object for reading the resource; {@code null} if
1349      *          the resource could not be found, a {@code URL} could not be
1350      *          constructed to locate the resource, the resource is in a package
1351      *          that is not opened unconditionally, or access to the resource is
1352      *          denied by the security manager.
1353      *
1354      * @throws  NullPointerException If {@code name} is {@code null}
1355      *
1356      * @since  1.1
1357      * @revised 9
1358      * @spec JPMS
1359      */
1360     public URL getResource(String name) {
1361         Objects.requireNonNull(name);
1362         URL url;
1363         if (parent != null) {
1364             url = parent.getResource(name);
1365         } else {
1366             url = BootLoader.findResource(name);
1367         }
1368         if (url == null) {
1369             url = findResource(name);
1370         }
1371         return url;
1372     }
1373 
1374     /**
1375      * Finds all the resources with the given name. A resource is some data
1376      * (images, audio, text, etc) that can be accessed by class code in a way
1377      * that is independent of the location of the code.
1378      *


1400      * {@code nextElement} method is the same resource that the
1401      * {@code getResource(String)} method would return.
1402      *
1403      * @param  name
1404      *         The resource name
1405      *
1406      * @return  An enumeration of {@link java.net.URL URL} objects for
1407      *          the resource. If no resources could  be found, the enumeration
1408      *          will be empty. Resources for which a {@code URL} cannot be
1409      *          constructed, are in package that is not opened unconditionally,
1410      *          or access to the resource is denied by the security manager,
1411      *          are not returned in the enumeration.
1412      *
1413      * @throws  IOException
1414      *          If I/O errors occur
1415      * @throws  NullPointerException If {@code name} is {@code null}
1416      *
1417      * @see  #findResources(String)
1418      *
1419      * @since  1.2
1420      * @revised 9
1421      * @spec JPMS
1422      */
1423     public Enumeration<URL> getResources(String name) throws IOException {
1424         Objects.requireNonNull(name);
1425         @SuppressWarnings("unchecked")
1426         Enumeration<URL>[] tmp = (Enumeration<URL>[]) new Enumeration<?>[2];
1427         if (parent != null) {
1428             tmp[0] = parent.getResources(name);
1429         } else {
1430             tmp[0] = BootLoader.findResources(name);
1431         }
1432         tmp[1] = findResources(name);
1433 
1434         return new CompoundEnumeration<>(tmp);
1435     }
1436 
1437     /**
1438      * Returns a stream whose elements are the URLs of all the resources with
1439      * the given name. A resource is some data (images, audio, text, etc) that
1440      * can be accessed by class code in a way that is independent of the
1441      * location of the code.


1498      * Finds the resource with the given name. Class loader implementations
1499      * should override this method to specify where to find resources.
1500      *
1501      * <p> For resources in named modules then the method must implement the
1502      * rules for encapsulation specified in the {@code Module} {@link
1503      * Module#getResourceAsStream getResourceAsStream} method. Additionally,
1504      * it must not find non-"{@code .class}" resources in packages of named
1505      * modules unless the package is {@link Module#isOpen(String) opened}
1506      * unconditionally. </p>
1507      *
1508      * @param  name
1509      *         The resource name
1510      *
1511      * @return  {@code URL} object for reading the resource; {@code null} if
1512      *          the resource could not be found, a {@code URL} could not be
1513      *          constructed to locate the resource, the resource is in a package
1514      *          that is not opened unconditionally, or access to the resource is
1515      *          denied by the security manager.
1516      *
1517      * @since  1.2
1518      * @revised 9
1519      * @spec JPMS
1520      */
1521     protected URL findResource(String name) {
1522         return null;
1523     }
1524 
1525     /**
1526      * Returns an enumeration of {@link java.net.URL URL} objects
1527      * representing all the resources with the given name. Class loader
1528      * implementations should override this method to specify where to load
1529      * resources from.
1530      *
1531      * <p> For resources in named modules then the method must implement the
1532      * rules for encapsulation specified in the {@code Module} {@link
1533      * Module#getResourceAsStream getResourceAsStream} method. Additionally,
1534      * it must not find non-"{@code .class}" resources in packages of named
1535      * modules unless the package is {@link Module#isOpen(String) opened}
1536      * unconditionally. </p>
1537      *
1538      * @param  name
1539      *         The resource name
1540      *
1541      * @return  An enumeration of {@link java.net.URL URL} objects for
1542      *          the resource. If no resources could  be found, the enumeration
1543      *          will be empty. Resources for which a {@code URL} cannot be
1544      *          constructed, are in a package that is not opened unconditionally,
1545      *          or access to the resource is denied by the security manager,
1546      *          are not returned in the enumeration.
1547      *
1548      * @throws  IOException
1549      *          If I/O errors occur
1550      *
1551      * @since  1.2
1552      * @revised 9
1553      * @spec JPMS
1554      */
1555     protected Enumeration<URL> findResources(String name) throws IOException {
1556         return Collections.emptyEnumeration();
1557     }
1558 
1559     /**
1560      * Registers the caller as
1561      * {@linkplain #isRegisteredAsParallelCapable() parallel capable}.
1562      * The registration succeeds if and only if all of the following
1563      * conditions are met:
1564      * <ol>
1565      * <li> no instance of the caller has been created</li>
1566      * <li> all of the super classes (except class Object) of the caller are
1567      * registered as parallel capable</li>
1568      * </ol>
1569      * <p>Note that once a class loader is registered as parallel capable, there
1570      * is no way to change it back.</p>
1571      *
1572      * @return  {@code true} if the caller is successfully registered as
1573      *          parallel capable and {@code false} if otherwise.


1604      * classes.  This method locates the resource through the system class
1605      * loader (see {@link #getSystemClassLoader()}).
1606      *
1607      * <p> Resources in named modules are subject to the encapsulation rules
1608      * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.
1609      * Additionally, and except for the special case where the resource has a
1610      * name ending with "{@code .class}", this method will only find resources in
1611      * packages of named modules when the package is {@link Module#isOpen(String)
1612      * opened} unconditionally. </p>
1613      *
1614      * @param  name
1615      *         The resource name
1616      *
1617      * @return  A {@link java.net.URL URL} to the resource; {@code
1618      *          null} if the resource could not be found, a URL could not be
1619      *          constructed to locate the resource, the resource is in a package
1620      *          that is not opened unconditionally or access to the resource is
1621      *          denied by the security manager.
1622      *
1623      * @since  1.1
1624      * @revised 9
1625      * @spec JPMS
1626      */
1627     public static URL getSystemResource(String name) {
1628         return getSystemClassLoader().getResource(name);
1629     }
1630 
1631     /**
1632      * Finds all resources of the specified name from the search path used to
1633      * load classes.  The resources thus found are returned as an
1634      * {@link java.util.Enumeration Enumeration} of {@link
1635      * java.net.URL URL} objects.
1636      *
1637      * <p> The search order is described in the documentation for {@link
1638      * #getSystemResource(String)}.  </p>
1639      *
1640      * <p> Resources in named modules are subject to the encapsulation rules
1641      * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.
1642      * Additionally, and except for the special case where the resource has a
1643      * name ending with "{@code .class}", this method will only find resources in
1644      * packages of named modules when the package is {@link Module#isOpen(String)
1645      * opened} unconditionally. </p>
1646      *
1647      * @param  name
1648      *         The resource name
1649      *
1650      * @return  An enumeration of {@link java.net.URL URL} objects for
1651      *          the resource. If no resources could  be found, the enumeration
1652      *          will be empty. Resources for which a {@code URL} cannot be
1653      *          constructed, are in a package that is not opened unconditionally,
1654      *          or access to the resource is denied by the security manager,
1655      *          are not returned in the enumeration.
1656      *
1657      * @throws  IOException
1658      *          If I/O errors occur
1659      *
1660      * @since  1.2
1661      * @revised 9
1662      * @spec JPMS
1663      */
1664     public static Enumeration<URL> getSystemResources(String name)
1665         throws IOException
1666     {
1667         return getSystemClassLoader().getResources(name);
1668     }
1669 
1670     /**
1671      * Returns an input stream for reading the specified resource.
1672      *
1673      * <p> The search order is described in the documentation for {@link
1674      * #getResource(String)}.  </p>
1675      *
1676      * <p> Resources in named modules are subject to the encapsulation rules
1677      * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.
1678      * Additionally, and except for the special case where the resource has a
1679      * name ending with "{@code .class}", this method will only find resources in
1680      * packages of named modules when the package is {@link Module#isOpen(String)
1681      * opened} unconditionally. </p>
1682      *
1683      * @param  name
1684      *         The resource name
1685      *
1686      * @return  An input stream for reading the resource; {@code null} if the
1687      *          resource could not be found, the resource is in a package that
1688      *          is not opened unconditionally, or access to the resource is
1689      *          denied by the security manager.
1690      *
1691      * @throws  NullPointerException If {@code name} is {@code null}
1692      *
1693      * @since  1.1
1694      * @revised 9
1695      * @spec JPMS
1696      */
1697     public InputStream getResourceAsStream(String name) {
1698         Objects.requireNonNull(name);
1699         URL url = getResource(name);
1700         try {
1701             return url != null ? url.openStream() : null;
1702         } catch (IOException e) {
1703             return null;
1704         }
1705     }
1706 
1707     /**
1708      * Open for reading, a resource of the specified name from the search path
1709      * used to load classes.  This method locates the resource through the
1710      * system class loader (see {@link #getSystemClassLoader()}).
1711      *
1712      * <p> Resources in named modules are subject to the encapsulation rules
1713      * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.
1714      * Additionally, and except for the special case where the resource has a
1715      * name ending with "{@code .class}", this method will only find resources in
1716      * packages of named modules when the package is {@link Module#isOpen(String)
1717      * opened} unconditionally. </p>
1718      *
1719      * @param  name
1720      *         The resource name
1721      *
1722      * @return  An input stream for reading the resource; {@code null} if the
1723      *          resource could not be found, the resource is in a package that
1724      *          is not opened unconditionally, or access to the resource is
1725      *          denied by the security manager.
1726      *
1727      * @since  1.1
1728      * @revised 9
1729      * @spec JPMS
1730      */
1731     public static InputStream getSystemResourceAsStream(String name) {
1732         URL url = getSystemResource(name);
1733         try {
1734             return url != null ? url.openStream() : null;
1735         } catch (IOException e) {
1736             return null;
1737         }
1738     }
1739 
1740 
1741     // -- Hierarchy --
1742 
1743     /**
1744      * Returns the parent class loader for delegation. Some implementations may
1745      * use {@code null} to represent the bootstrap class loader. This method
1746      * will return {@code null} in such implementations if this class loader's
1747      * parent is the bootstrap class loader.
1748      *
1749      * @return  The parent {@code ClassLoader}


1760     public final ClassLoader getParent() {
1761         if (parent == null)
1762             return null;
1763         SecurityManager sm = System.getSecurityManager();
1764         if (sm != null) {
1765             // Check access to the parent class loader
1766             // If the caller's class loader is same as this class loader,
1767             // permission check is performed.
1768             checkClassLoaderPermission(parent, Reflection.getCallerClass());
1769         }
1770         return parent;
1771     }
1772 
1773     /**
1774      * Returns the unnamed {@code Module} for this class loader.
1775      *
1776      * @return The unnamed Module for this class loader
1777      *
1778      * @see Module#isNamed()
1779      * @since 9
1780      * @spec JPMS
1781      */
1782     public final Module getUnnamedModule() {
1783         return unnamedModule;
1784     }
1785 
1786     /**
1787      * Returns the platform class loader for delegation.  All
1788      * <a href="#builtinLoaders">platform classes</a> are visible to
1789      * the platform class loader.
1790      *
1791      * @implNote The name of the builtin platform class loader is
1792      * {@code "platform"}.
1793      *
1794      * @return  The platform {@code ClassLoader}.
1795      *
1796      * @throws  SecurityException
1797      *          If a security manager is present, and the caller's class loader is
1798      *          not {@code null}, and the caller's class loader is not the same
1799      *          as or an ancestor of the platform class loader,
1800      *          and the caller does not have the
1801      *          {@link RuntimePermission}{@code ("getClassLoader")}
1802      *
1803      * @since 9
1804      * @spec JPMS
1805      */
1806     @CallerSensitive
1807     public static ClassLoader getPlatformClassLoader() {
1808         SecurityManager sm = System.getSecurityManager();
1809         ClassLoader loader = getBuiltinPlatformClassLoader();
1810         if (sm != null) {
1811             checkClassLoaderPermission(loader, Reflection.getCallerClass());
1812         }
1813         return loader;
1814     }
1815 
1816     /**
1817      * Returns the system class loader for delegation.  This is the default
1818      * delegation parent for new {@code ClassLoader} instances, and is
1819      * typically the class loader used to start the application.
1820      *
1821      * <p> This method is first invoked early in the runtime's startup
1822      * sequence, at which point it creates the system class loader. This
1823      * class loader will be the context class loader for the main application
1824      * thread (for example, the thread that invokes the {@code main} method of


1860      * @throws  SecurityException
1861      *          If a security manager is present, and the caller's class loader
1862      *          is not {@code null} and is not the same as or an ancestor of the
1863      *          system class loader, and the caller does not have the
1864      *          {@link RuntimePermission}{@code ("getClassLoader")}
1865      *
1866      * @throws  IllegalStateException
1867      *          If invoked recursively during the construction of the class
1868      *          loader specified by the "{@code java.system.class.loader}"
1869      *          property.
1870      *
1871      * @throws  Error
1872      *          If the system property "{@code java.system.class.loader}"
1873      *          is defined but the named class could not be loaded, the
1874      *          provider class does not define the required constructor, or an
1875      *          exception is thrown by that constructor when it is invoked. The
1876      *          underlying cause of the error can be retrieved via the
1877      *          {@link Throwable#getCause()} method.
1878      *
1879      * @revised  1.4
1880      * @revised 9
1881      * @spec JPMS
1882      */
1883     @CallerSensitive
1884     public static ClassLoader getSystemClassLoader() {
1885         switch (VM.initLevel()) {
1886             case 0:
1887             case 1:
1888             case 2:
1889                 // the system class loader is the built-in app class loader during startup
1890                 return getBuiltinAppClassLoader();
1891             case 3:
1892                 throw new InternalError("getSystemClassLoader should only be called after VM booted");
1893             case 4:
1894                 // system fully initialized
1895                 assert VM.isBooted() && scl != null;
1896                 SecurityManager sm = System.getSecurityManager();
1897                 if (sm != null) {
1898                     checkClassLoaderPermission(scl, Reflection.getCallerClass());
1899                 }
1900                 return scl;
1901             default:


2116      *         The implementation version
2117      *
2118      * @param  implVendor
2119      *         The implementation vendor
2120      *
2121      * @param  sealBase
2122      *         If not {@code null}, then this package is sealed with
2123      *         respect to the given code source {@link java.net.URL URL}
2124      *         object.  Otherwise, the package is not sealed.
2125      *
2126      * @return  The newly defined {@code Package} object
2127      *
2128      * @throws  NullPointerException
2129      *          if {@code name} is {@code null}.
2130      *
2131      * @throws  IllegalArgumentException
2132      *          if a package of the given {@code name} is already
2133      *          defined by this class loader
2134      *
2135      * @since  1.2
2136      * @revised 9
2137      * @spec JPMS
2138      *
2139      * @see <a href="../../../technotes/guides/jar/jar.html#versioning">
2140      *      The JAR File Specification: Package Versioning</a>
2141      * @see <a href="../../../technotes/guides/jar/jar.html#sealing">
2142      *      The JAR File Specification: Package Sealing</a>
2143      */
2144     protected Package definePackage(String name, String specTitle,
2145                                     String specVersion, String specVendor,
2146                                     String implTitle, String implVersion,
2147                                     String implVendor, URL sealBase)
2148     {
2149         Objects.requireNonNull(name);
2150 
2151         // definePackage is not final and may be overridden by custom class loader
2152         Package p = new Package(name, specTitle, specVersion, specVendor,
2153                                 implTitle, implVersion, implVendor,
2154                                 sealBase, this);
2155 
2156         if (packages.putIfAbsent(name, p) != null)
2157             throw new IllegalArgumentException(name);
2158 
2159         return p;
2160     }
2161 
2162     /**
2163      * Returns a {@code Package} of the given <a href="#name">name</a> that has been
2164      * defined by this class loader.
2165      *
2166      * @param  name The <a href="#name">package name</a>
2167      *
2168      * @return The {@code Package} of the given name defined by this class loader,
2169      *         or {@code null} if not found
2170      *
2171      * @throws  NullPointerException
2172      *          if {@code name} is {@code null}.
2173      *
2174      * @since  9
2175      * @spec JPMS
2176      */
2177     public final Package getDefinedPackage(String name) {
2178         Objects.requireNonNull(name, "name cannot be null");
2179 
2180         NamedPackage p = packages.get(name);
2181         if (p == null)
2182             return null;
2183 
2184         return definePackage(name, p.module());
2185     }
2186 
2187     /**
2188      * Returns all of the {@code Package}s defined by this class loader.
2189      * The returned array has no duplicated {@code Package}s of the same name.
2190      *
2191      * @apiNote This method returns an array rather than a {@code Set} or {@code Stream}
2192      *          for consistency with the existing {@link #getPackages} method.
2193      *
2194      * @return The array of {@code Package} objects defined by this class loader;
2195      *         or an zero length array if no package has been defined by this class loader.
2196      *
2197      * @since  9
2198      * @spec JPMS
2199      */
2200     public final Package[] getDefinedPackages() {
2201         return packages().toArray(Package[]::new);
2202     }
2203 
2204     /**
2205      * Finds a package by <a href="#name">name</a> in this class loader and its ancestors.
2206      * <p>
2207      * If this class loader defines a {@code Package} of the given name,
2208      * the {@code Package} is returned. Otherwise, the ancestors of
2209      * this class loader are searched recursively (parent by parent)
2210      * for a {@code Package} of the given name.
2211      *
2212      * @param  name
2213      *         The <a href="#name">package name</a>
2214      *
2215      * @return The {@code Package} corresponding to the given name defined by
2216      *         this class loader or its ancestors, or {@code null} if not found.
2217      *
2218      * @throws  NullPointerException
2219      *          if {@code name} is {@code null}.
2220      *
2221      * @deprecated
2222      * If multiple class loaders delegate to each other and define classes
2223      * with the same package name, and one such loader relies on the lookup
2224      * behavior of {@code getPackage} to return a {@code Package} from
2225      * a parent loader, then the properties exposed by the {@code Package}
2226      * may not be as expected in the rest of the program.
2227      * For example, the {@code Package} will only expose annotations from the
2228      * {@code package-info.class} file defined by the parent loader, even if
2229      * annotations exist in a {@code package-info.class} file defined by
2230      * a child loader.  A more robust approach is to use the
2231      * {@link ClassLoader#getDefinedPackage} method which returns
2232      * a {@code Package} for the specified class loader.
2233      *
2234      * @since  1.2
2235      * @revised 9
2236      * @spec JPMS
2237      */
2238     @Deprecated(since="9")
2239     protected Package getPackage(String name) {
2240         Package pkg = getDefinedPackage(name);
2241         if (pkg == null) {
2242             if (parent != null) {
2243                 pkg = parent.getPackage(name);
2244             } else {
2245                 pkg = BootLoader.getDefinedPackage(name);
2246             }
2247         }
2248         return pkg;
2249     }
2250 
2251     /**
2252      * Returns all of the {@code Package}s defined by this class loader
2253      * and its ancestors.  The returned array may contain more than one
2254      * {@code Package} object of the same package name, each defined by
2255      * a different class loader in the class loader hierarchy.
2256      *
2257      * @return  The array of {@code Package} objects defined by this
2258      *          class loader and its ancestors
2259      *
2260      * @since  1.2
2261      * @revised 9
2262      * @spec JPMS
2263      */
2264     protected Package[] getPackages() {
2265         Stream<Package> pkgs = packages();
2266         ClassLoader ld = parent;
2267         while (ld != null) {
2268             pkgs = Stream.concat(ld.packages(), pkgs);
2269             ld = ld.parent;
2270         }
2271         return Stream.concat(BootLoader.packages(), pkgs)
2272                      .toArray(Package[]::new);
2273     }
2274 
2275 
2276 
2277     // package-private
2278 
2279     /**
2280      * Returns a stream of Packages defined in this class loader
2281      */
2282     Stream<Package> packages() {


< prev index next >