• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2014 The Android Open Source Project
3  * Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved.
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This code is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License version 2 only, as
8  * published by the Free Software Foundation.  Oracle designates this
9  * particular file as subject to the "Classpath" exception as provided
10  * by Oracle in the LICENSE file that accompanied this code.
11  *
12  * This code is distributed in the hope that it will be useful, but WITHOUT
13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15  * version 2 for more details (a copy is included in the LICENSE file that
16  * accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License version
19  * 2 along with this work; if not, write to the Free Software Foundation,
20  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21  *
22  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
23  * or visit www.oracle.com if you need additional information or have any
24  * questions.
25  */
26 package java.lang;
27 
28 import java.io.InputStream;
29 import java.io.IOException;
30 import java.io.File;
31 import java.lang.reflect.Constructor;
32 import java.lang.reflect.InvocationTargetException;
33 import java.net.MalformedURLException;
34 import java.net.URL;
35 import java.security.AccessController;
36 import java.security.AccessControlContext;
37 import java.security.CodeSource;
38 import java.security.Policy;
39 import java.security.PrivilegedAction;
40 import java.security.PrivilegedActionException;
41 import java.security.PrivilegedExceptionAction;
42 import java.security.ProtectionDomain;
43 import java.security.cert.Certificate;
44 import java.util.Collections;
45 import java.util.Enumeration;
46 import java.util.HashMap;
47 import java.util.HashSet;
48 import java.util.Set;
49 import java.util.Stack;
50 import java.util.Map;
51 import java.util.Vector;
52 import java.util.Hashtable;
53 import java.util.WeakHashMap;
54 import java.util.concurrent.ConcurrentHashMap;
55 import dalvik.system.PathClassLoader;
56 import java.util.List;
57 import sun.misc.CompoundEnumeration;
58 import sun.misc.Resource;
59 import sun.misc.URLClassPath;
60 import sun.misc.VM;
61 import sun.reflect.CallerSensitive;
62 import sun.reflect.Reflection;
63 import sun.security.util.SecurityConstants;
64 
65 /**
66  * A class loader is an object that is responsible for loading classes. The
67  * class <tt>ClassLoader</tt> is an abstract class.  Given the <a
68  * href="#name">binary name</a> of a class, a class loader should attempt to
69  * locate or generate data that constitutes a definition for the class.  A
70  * typical strategy is to transform the name into a file name and then read a
71  * "class file" of that name from a file system.
72  *
73  * <p> Every {@link Class <tt>Class</tt>} object contains a {@link
74  * Class#getClassLoader() reference} to the <tt>ClassLoader</tt> that defined
75  * it.
76  *
77  * <p> <tt>Class</tt> objects for array classes are not created by class
78  * loaders, but are created automatically as required by the Java runtime.
79  * The class loader for an array class, as returned by {@link
80  * Class#getClassLoader()} is the same as the class loader for its element
81  * type; if the element type is a primitive type, then the array class has no
82  * class loader.
83  *
84  * <p> Applications implement subclasses of <tt>ClassLoader</tt> in order to
85  * extend the manner in which the Java virtual machine dynamically loads
86  * classes.
87  *
88  * <p> Class loaders may typically be used by security managers to indicate
89  * security domains.
90  *
91  * <p> The <tt>ClassLoader</tt> class uses a delegation model to search for
92  * classes and resources.  Each instance of <tt>ClassLoader</tt> has an
93  * associated parent class loader.  When requested to find a class or
94  * resource, a <tt>ClassLoader</tt> instance will delegate the search for the
95  * class or resource to its parent class loader before attempting to find the
96  * class or resource itself.  The virtual machine's built-in class loader,
97  * called the "bootstrap class loader", does not itself have a parent but may
98  * serve as the parent of a <tt>ClassLoader</tt> instance.
99  *
100  * <p> Class loaders that support concurrent loading of classes are known as
101  * <em>parallel capable</em> class loaders and are required to register
102  * themselves at their class initialization time by invoking the
103  * {@link
104  * #registerAsParallelCapable <tt>ClassLoader.registerAsParallelCapable</tt>}
105  * method. Note that the <tt>ClassLoader</tt> class is registered as parallel
106  * capable by default. However, its subclasses still need to register themselves
107  * if they are parallel capable. <br>
108  * In environments in which the delegation model is not strictly
109  * hierarchical, class loaders need to be parallel capable, otherwise class
110  * loading can lead to deadlocks because the loader lock is held for the
111  * duration of the class loading process (see {@link #loadClass
112  * <tt>loadClass</tt>} methods).
113  *
114  * <p> Normally, the Java virtual machine loads classes from the local file
115  * system in a platform-dependent manner.  For example, on UNIX systems, the
116  * virtual machine loads classes from the directory defined by the
117  * <tt>CLASSPATH</tt> environment variable.
118  *
119  * <p> However, some classes may not originate from a file; they may originate
120  * from other sources, such as the network, or they could be constructed by an
121  * application.  The method {@link #defineClass(String, byte[], int, int)
122  * <tt>defineClass</tt>} converts an array of bytes into an instance of class
123  * <tt>Class</tt>. Instances of this newly defined class can be created using
124  * {@link Class#newInstance <tt>Class.newInstance</tt>}.
125  *
126  * <p> The methods and constructors of objects created by a class loader may
127  * reference other classes.  To determine the class(es) referred to, the Java
128  * virtual machine invokes the {@link #loadClass <tt>loadClass</tt>} method of
129  * the class loader that originally created the class.
130  *
131  * <p> For example, an application could create a network class loader to
132  * download class files from a server.  Sample code might look like:
133  *
134  * <blockquote><pre>
135  *   ClassLoader loader&nbsp;= new NetworkClassLoader(host,&nbsp;port);
136  *   Object main&nbsp;= loader.loadClass("Main", true).newInstance();
137  *       &nbsp;.&nbsp;.&nbsp;.
138  * </pre></blockquote>
139  *
140  * <p> The network class loader subclass must define the methods {@link
141  * #findClass <tt>findClass</tt>} and <tt>loadClassData</tt> to load a class
142  * from the network.  Once it has downloaded the bytes that make up the class,
143  * it should use the method {@link #defineClass <tt>defineClass</tt>} to
144  * create a class instance.  A sample implementation is:
145  *
146  * <blockquote><pre>
147  *     class NetworkClassLoader extends ClassLoader {
148  *         String host;
149  *         int port;
150  *
151  *         public Class findClass(String name) {
152  *             byte[] b = loadClassData(name);
153  *             return defineClass(name, b, 0, b.length);
154  *         }
155  *
156  *         private byte[] loadClassData(String name) {
157  *             // load the class data from the connection
158  *             &nbsp;.&nbsp;.&nbsp;.
159  *         }
160  *     }
161  * </pre></blockquote>
162  *
163  * <h3> <a name="name">Binary names</a> </h3>
164  *
165  * <p> Any class name provided as a {@link String} parameter to methods in
166  * <tt>ClassLoader</tt> must be a binary name as defined by
167  * <cite>The Java&trade; Language Specification</cite>.
168  *
169  * <p> Examples of valid class names include:
170  * <blockquote><pre>
171  *   "java.lang.String"
172  *   "javax.swing.JSpinner$DefaultEditor"
173  *   "java.security.KeyStore$Builder$FileBuilder$1"
174  *   "java.net.URLClassLoader$3$1"
175  * </pre></blockquote>
176  *
177  * @see      #resolveClass(Class)
178  * @since 1.0
179  */
180 public abstract class ClassLoader {
181 
182     static private class SystemClassLoader {
183         public static ClassLoader loader = ClassLoader.createSystemClassLoader();
184     }
185 
186     /**
187      * To avoid unloading individual classes, {@link java.lang.reflect.Proxy}
188      * only generates one class for each set of interfaces. This maps sets of
189      * interfaces to the proxy class that implements all of them. It is declared
190      * here so that these generated classes can be unloaded with their class
191      * loader.
192      *
193      * @hide
194      */
195     public final Map<List<Class<?>>, Class<?>> proxyCache =
196             new HashMap<List<Class<?>>, Class<?>>();
197 
198     // The parent class loader for delegation
199     // Note: VM hardcoded the offset of this field, thus all new fields
200     // must be added *after* it.
201     private final ClassLoader parent;
202 
203     /**
204      * Encapsulates the set of parallel capable loader types.
205      */
createSystemClassLoader()206     private static ClassLoader createSystemClassLoader() {
207         String classPath = System.getProperty("java.class.path", ".");
208         String librarySearchPath = System.getProperty("java.library.path", "");
209 
210         // String[] paths = classPath.split(":");
211         // URL[] urls = new URL[paths.length];
212         // for (int i = 0; i < paths.length; i++) {
213         // try {
214         // urls[i] = new URL("file://" + paths[i]);
215         // }
216         // catch (Exception ex) {
217         // ex.printStackTrace();
218         // }
219         // }
220         //
221         // return new java.net.URLClassLoader(urls, null);
222 
223         // TODO Make this a java.net.URLClassLoader once we have those?
224         return new PathClassLoader(classPath, librarySearchPath, BootClassLoader.getInstance());
225     }
226 
227     // The packages defined in this class loader.  Each package name is mapped
228     // to its corresponding Package object.
229     // @GuardedBy("itself")
230     private final HashMap<String, Package> packages = new HashMap<>();
231 
232     /**
233      * Pointer to the allocator used by the runtime to allocate metadata such
234      * as ArtFields and ArtMethods.
235      */
236     private transient long allocator;
237 
238     /**
239      * Pointer to the class table, only used from within the runtime.
240      */
241     private transient long classTable;
242 
checkCreateClassLoader()243     private static Void checkCreateClassLoader() {
244         return null;
245     }
246 
ClassLoader(Void unused, ClassLoader parent)247     private ClassLoader(Void unused, ClassLoader parent) {
248         this.parent = parent;
249     }
250 
251     /**
252      * Creates a new class loader using the specified parent class loader for
253      * delegation.
254      *
255      * <p> If there is a security manager, its {@link
256      * SecurityManager#checkCreateClassLoader()
257      * <tt>checkCreateClassLoader</tt>} method is invoked.  This may result in
258      * a security exception.  </p>
259      *
260      * @param  parent
261      *         The parent class loader
262      *
263      * @throws  SecurityException
264      *          If a security manager exists and its
265      *          <tt>checkCreateClassLoader</tt> method doesn't allow creation
266      *          of a new class loader.
267      *
268      * @since  1.2
269      */
ClassLoader(ClassLoader parent)270     protected ClassLoader(ClassLoader parent) {
271         this(checkCreateClassLoader(), parent);
272     }
273 
274     /**
275      * Creates a new class loader using the <tt>ClassLoader</tt> returned by
276      * the method {@link #getSystemClassLoader()
277      * <tt>getSystemClassLoader()</tt>} as the parent class loader.
278      *
279      * <p> If there is a security manager, its {@link
280      * SecurityManager#checkCreateClassLoader()
281      * <tt>checkCreateClassLoader</tt>} method is invoked.  This may result in
282      * a security exception.  </p>
283      *
284      * @throws  SecurityException
285      *          If a security manager exists and its
286      *          <tt>checkCreateClassLoader</tt> method doesn't allow creation
287      *          of a new class loader.
288      */
ClassLoader()289     protected ClassLoader() {
290         this(checkCreateClassLoader(), getSystemClassLoader());
291     }
292 
293     // -- Class --
294 
295     /**
296      * Loads the class with the specified <a href="#name">binary name</a>.
297      * This method searches for classes in the same manner as the {@link
298      * #loadClass(String, boolean)} method.  It is invoked by the Java virtual
299      * machine to resolve class references.  Invoking this method is equivalent
300      * to invoking {@link #loadClass(String, boolean) <tt>loadClass(name,
301      * false)</tt>}.
302      *
303      * @param  name
304      *         The <a href="#name">binary name</a> of the class
305      *
306      * @return  The resulting <tt>Class</tt> object
307      *
308      * @throws  ClassNotFoundException
309      *          If the class was not found
310      */
loadClass(String name)311     public Class<?> loadClass(String name) throws ClassNotFoundException {
312         return loadClass(name, false);
313     }
314 
315     /**
316      * Loads the class with the specified <a href="#name">binary name</a>.  The
317      * default implementation of this method searches for classes in the
318      * following order:
319      *
320      * <ol>
321      *
322      *   <li><p> Invoke {@link #findLoadedClass(String)} to check if the class
323      *   has already been loaded.  </p></li>
324      *
325      *   <li><p> Invoke the {@link #loadClass(String) <tt>loadClass</tt>} method
326      *   on the parent class loader.  If the parent is <tt>null</tt> the class
327      *   loader built-in to the virtual machine is used, instead.  </p></li>
328      *
329      *   <li><p> Invoke the {@link #findClass(String)} method to find the
330      *   class.  </p></li>
331      *
332      * </ol>
333      *
334      * <p> If the class was found using the above steps, and the
335      * <tt>resolve</tt> flag is true, this method will then invoke the {@link
336      * #resolveClass(Class)} method on the resulting <tt>Class</tt> object.
337      *
338      * <p> Subclasses of <tt>ClassLoader</tt> are encouraged to override {@link
339      * #findClass(String)}, rather than this method.  </p>
340      *
341      *
342      * @param  name
343      *         The <a href="#name">binary name</a> of the class
344      *
345      * @param  resolve
346      *         If <tt>true</tt> then resolve the class
347      *
348      * @return  The resulting <tt>Class</tt> object
349      *
350      * @throws  ClassNotFoundException
351      *          If the class could not be found
352      */
353     // Android-removed: Remove references to getClassLoadingLock
354     //                   Remove perf counters.
355     //
356     // <p> Unless overridden, this method synchronizes on the result of
357     // {@link #getClassLoadingLock <tt>getClassLoadingLock</tt>} method
358     // during the entire class loading process.
loadClass(String name, boolean resolve)359     protected Class<?> loadClass(String name, boolean resolve)
360         throws ClassNotFoundException
361     {
362             // First, check if the class has already been loaded
363             Class<?> c = findLoadedClass(name);
364             if (c == null) {
365                 try {
366                     if (parent != null) {
367                         c = parent.loadClass(name, false);
368                     } else {
369                         c = findBootstrapClassOrNull(name);
370                     }
371                 } catch (ClassNotFoundException e) {
372                     // ClassNotFoundException thrown if class not found
373                     // from the non-null parent class loader
374                 }
375 
376                 if (c == null) {
377                     // If still not found, then invoke findClass in order
378                     // to find the class.
379                     c = findClass(name);
380                 }
381             }
382             return c;
383     }
384 
385 
386     /**
387      * Finds the class with the specified <a href="#name">binary name</a>.
388      * This method should be overridden by class loader implementations that
389      * follow the delegation model for loading classes, and will be invoked by
390      * the {@link #loadClass <tt>loadClass</tt>} method after checking the
391      * parent class loader for the requested class.  The default implementation
392      * throws a <tt>ClassNotFoundException</tt>.
393      *
394      * @param  name
395      *         The <a href="#name">binary name</a> of the class
396      *
397      * @return  The resulting <tt>Class</tt> object
398      *
399      * @throws  ClassNotFoundException
400      *          If the class could not be found
401      *
402      * @since  1.2
403      */
findClass(String name)404     protected Class<?> findClass(String name) throws ClassNotFoundException {
405         throw new ClassNotFoundException(name);
406     }
407 
408     /**
409      * Converts an array of bytes into an instance of class <tt>Class</tt>.
410      * Before the <tt>Class</tt> can be used it must be resolved.  This method
411      * is deprecated in favor of the version that takes a <a
412      * href="#name">binary name</a> as its first argument, and is more secure.
413      *
414      * @param  b
415      *         The bytes that make up the class data.  The bytes in positions
416      *         <tt>off</tt> through <tt>off+len-1</tt> should have the format
417      *         of a valid class file as defined by
418      *         <cite>The Java&trade; Virtual Machine Specification</cite>.
419      *
420      * @param  off
421      *         The start offset in <tt>b</tt> of the class data
422      *
423      * @param  len
424      *         The length of the class data
425      *
426      * @return  The <tt>Class</tt> object that was created from the specified
427      *          class data
428      *
429      * @throws  ClassFormatError
430      *          If the data did not contain a valid class
431      *
432      * @throws  IndexOutOfBoundsException
433      *          If either <tt>off</tt> or <tt>len</tt> is negative, or if
434      *          <tt>off+len</tt> is greater than <tt>b.length</tt>.
435      *
436      * @throws  SecurityException
437      *          If an attempt is made to add this class to a package that
438      *          contains classes that were signed by a different set of
439      *          certificates than this class, or if an attempt is made
440      *          to define a class in a package with a fully-qualified name
441      *          that starts with "{@code java.}".
442      *
443      * @see  #loadClass(String, boolean)
444      * @see  #resolveClass(Class)
445      *
446      * @deprecated  Replaced by {@link #defineClass(String, byte[], int, int)
447      * defineClass(String, byte[], int, int)}
448      */
449     @Deprecated
defineClass(byte[] b, int off, int len)450     protected final Class<?> defineClass(byte[] b, int off, int len)
451         throws ClassFormatError
452     {
453         throw new UnsupportedOperationException("can't load this type of class file");
454     }
455 
456     /**
457      * Converts an array of bytes into an instance of class <tt>Class</tt>.
458      * Before the <tt>Class</tt> can be used it must be resolved.
459      *
460      * <p> This method assigns a default {@link java.security.ProtectionDomain
461      * <tt>ProtectionDomain</tt>} to the newly defined class.  The
462      * <tt>ProtectionDomain</tt> is effectively granted the same set of
463      * permissions returned when {@link
464      * java.security.Policy#getPermissions(java.security.CodeSource)
465      * <tt>Policy.getPolicy().getPermissions(new CodeSource(null, null))</tt>}
466      * is invoked.  The default domain is created on the first invocation of
467      * {@link #defineClass(String, byte[], int, int) <tt>defineClass</tt>},
468      * and re-used on subsequent invocations.
469      *
470      * <p> To assign a specific <tt>ProtectionDomain</tt> to the class, use
471      * the {@link #defineClass(String, byte[], int, int,
472      * java.security.ProtectionDomain) <tt>defineClass</tt>} method that takes a
473      * <tt>ProtectionDomain</tt> as one of its arguments.  </p>
474      *
475      * @param  name
476      *         The expected <a href="#name">binary name</a> of the class, or
477      *         <tt>null</tt> if not known
478      *
479      * @param  b
480      *         The bytes that make up the class data.  The bytes in positions
481      *         <tt>off</tt> through <tt>off+len-1</tt> should have the format
482      *         of a valid class file as defined by
483      *         <cite>The Java&trade; Virtual Machine Specification</cite>.
484      *
485      * @param  off
486      *         The start offset in <tt>b</tt> of the class data
487      *
488      * @param  len
489      *         The length of the class data
490      *
491      * @return  The <tt>Class</tt> object that was created from the specified
492      *          class data.
493      *
494      * @throws  ClassFormatError
495      *          If the data did not contain a valid class
496      *
497      * @throws  IndexOutOfBoundsException
498      *          If either <tt>off</tt> or <tt>len</tt> is negative, or if
499      *          <tt>off+len</tt> is greater than <tt>b.length</tt>.
500      *
501      * @throws  SecurityException
502      *          If an attempt is made to add this class to a package that
503      *          contains classes that were signed by a different set of
504      *          certificates than this class (which is unsigned), or if
505      *          <tt>name</tt> begins with "<tt>java.</tt>".
506      *
507      * @see  #loadClass(String, boolean)
508      * @see  #resolveClass(Class)
509      * @see  java.security.CodeSource
510      * @see  java.security.SecureClassLoader
511      *
512      * @since  1.1
513      */
defineClass(String name, byte[] b, int off, int len)514     protected final Class<?> defineClass(String name, byte[] b, int off, int len)
515         throws ClassFormatError
516     {
517         throw new UnsupportedOperationException("can't load this type of class file");
518     }
519 
520 
521     /**
522      * Converts an array of bytes into an instance of class <tt>Class</tt>,
523      * with an optional <tt>ProtectionDomain</tt>.  If the domain is
524      * <tt>null</tt>, then a default domain will be assigned to the class as
525      * specified in the documentation for {@link #defineClass(String, byte[],
526      * int, int)}.  Before the class can be used it must be resolved.
527      *
528      * <p> The first class defined in a package determines the exact set of
529      * certificates that all subsequent classes defined in that package must
530      * contain.  The set of certificates for a class is obtained from the
531      * {@link java.security.CodeSource <tt>CodeSource</tt>} within the
532      * <tt>ProtectionDomain</tt> of the class.  Any classes added to that
533      * package must contain the same set of certificates or a
534      * <tt>SecurityException</tt> will be thrown.  Note that if
535      * <tt>name</tt> is <tt>null</tt>, this check is not performed.
536      * You should always pass in the <a href="#name">binary name</a> of the
537      * class you are defining as well as the bytes.  This ensures that the
538      * class you are defining is indeed the class you think it is.
539      *
540      * <p> The specified <tt>name</tt> cannot begin with "<tt>java.</tt>", since
541      * all classes in the "<tt>java.*</tt> packages can only be defined by the
542      * bootstrap class loader.  If <tt>name</tt> is not <tt>null</tt>, it
543      * must be equal to the <a href="#name">binary name</a> of the class
544      * specified by the byte array "<tt>b</tt>", otherwise a {@link
545      * NoClassDefFoundError <tt>NoClassDefFoundError</tt>} will be thrown. </p>
546      *
547      * @param  name
548      *         The expected <a href="#name">binary name</a> of the class, or
549      *         <tt>null</tt> if not known
550      *
551      * @param  b
552      *         The bytes that make up the class data. The bytes in positions
553      *         <tt>off</tt> through <tt>off+len-1</tt> should have the format
554      *         of a valid class file as defined by
555      *         <cite>The Java&trade; Virtual Machine Specification</cite>.
556      *
557      * @param  off
558      *         The start offset in <tt>b</tt> of the class data
559      *
560      * @param  len
561      *         The length of the class data
562      *
563      * @param  protectionDomain
564      *         The ProtectionDomain of the class
565      *
566      * @return  The <tt>Class</tt> object created from the data,
567      *          and optional <tt>ProtectionDomain</tt>.
568      *
569      * @throws  ClassFormatError
570      *          If the data did not contain a valid class
571      *
572      * @throws  NoClassDefFoundError
573      *          If <tt>name</tt> is not equal to the <a href="#name">binary
574      *          name</a> of the class specified by <tt>b</tt>
575      *
576      * @throws  IndexOutOfBoundsException
577      *          If either <tt>off</tt> or <tt>len</tt> is negative, or if
578      *          <tt>off+len</tt> is greater than <tt>b.length</tt>.
579      *
580      * @throws  SecurityException
581      *          If an attempt is made to add this class to a package that
582      *          contains classes that were signed by a different set of
583      *          certificates than this class, or if <tt>name</tt> begins with
584      *          "<tt>java.</tt>".
585      */
586     // Android-changed: Remove <tt> from link for NoClassDefFoundError
defineClass(String name, byte[] b, int off, int len, ProtectionDomain protectionDomain)587     protected final Class<?> defineClass(String name, byte[] b, int off, int len,
588                                          ProtectionDomain protectionDomain)
589         throws ClassFormatError
590     {
591         throw new UnsupportedOperationException("can't load this type of class file");
592     }
593 
594     /**
595      * Converts a {@link java.nio.ByteBuffer <tt>ByteBuffer</tt>}
596      * into an instance of class <tt>Class</tt>,
597      * with an optional <tt>ProtectionDomain</tt>.  If the domain is
598      * <tt>null</tt>, then a default domain will be assigned to the class as
599      * specified in the documentation for {@link #defineClass(String, byte[],
600      * int, int)}.  Before the class can be used it must be resolved.
601      *
602      * <p>The rules about the first class defined in a package determining the
603      * set of certificates for the package, and the restrictions on class names
604      * are identical to those specified in the documentation for {@link
605      * #defineClass(String, byte[], int, int, ProtectionDomain)}.
606      *
607      * <p> An invocation of this method of the form
608      * <i>cl</i><tt>.defineClass(</tt><i>name</i><tt>,</tt>
609      * <i>bBuffer</i><tt>,</tt> <i>pd</i><tt>)</tt> yields exactly the same
610      * result as the statements
611      *
612      *<p> <tt>
613      * ...<br>
614      * byte[] temp = new byte[bBuffer.{@link
615      * java.nio.ByteBuffer#remaining remaining}()];<br>
616      *     bBuffer.{@link java.nio.ByteBuffer#get(byte[])
617      * get}(temp);<br>
618      *     return {@link #defineClass(String, byte[], int, int, ProtectionDomain)
619      * cl.defineClass}(name, temp, 0,
620      * temp.length, pd);<br>
621      * </tt></p>
622      *
623      * @param  name
624      *         The expected <a href="#name">binary name</a>. of the class, or
625      *         <tt>null</tt> if not known
626      *
627      * @param  b
628      *         The bytes that make up the class data. The bytes from positions
629      *         <tt>b.position()</tt> through <tt>b.position() + b.limit() -1
630      *         </tt> should have the format of a valid class file as defined by
631      *         <cite>The Java&trade; Virtual Machine Specification</cite>.
632      *
633      * @param  protectionDomain
634      *         The ProtectionDomain of the class, or <tt>null</tt>.
635      *
636      * @return  The <tt>Class</tt> object created from the data,
637      *          and optional <tt>ProtectionDomain</tt>.
638      *
639      * @throws  ClassFormatError
640      *          If the data did not contain a valid class.
641      *
642      * @throws  NoClassDefFoundError
643      *          If <tt>name</tt> is not equal to the <a href="#name">binary
644      *          name</a> of the class specified by <tt>b</tt>
645      *
646      * @throws  SecurityException
647      *          If an attempt is made to add this class to a package that
648      *          contains classes that were signed by a different set of
649      *          certificates than this class, or if <tt>name</tt> begins with
650      *          "<tt>java.</tt>".
651      *
652      * @see      #defineClass(String, byte[], int, int, ProtectionDomain)
653      *
654      * @since  1.5
655      */
defineClass(String name, java.nio.ByteBuffer b, ProtectionDomain protectionDomain)656     protected final Class<?> defineClass(String name, java.nio.ByteBuffer b,
657                                          ProtectionDomain protectionDomain)
658         throws ClassFormatError
659     {
660         throw new UnsupportedOperationException("can't load this type of class file");
661     }
662 
663     /**
664      * Links the specified class.  This (misleadingly named) method may be
665      * used by a class loader to link a class.  If the class <tt>c</tt> has
666      * already been linked, then this method simply returns. Otherwise, the
667      * class is linked as described in the "Execution" chapter of
668      * <cite>The Java&trade; Language Specification</cite>.
669      *
670      * @param  c
671      *         The class to link
672      *
673      * @throws  NullPointerException
674      *          If <tt>c</tt> is <tt>null</tt>.
675      *
676      * @see  #defineClass(String, byte[], int, int)
677      */
resolveClass(Class<?> c)678     protected final void resolveClass(Class<?> c) {
679     }
680 
681     /**
682      * Finds a class with the specified <a href="#name">binary name</a>,
683      * loading it if necessary.
684      *
685      * <p> This method loads the class through the system class loader (see
686      * {@link #getSystemClassLoader()}).  The <tt>Class</tt> object returned
687      * might have more than one <tt>ClassLoader</tt> associated with it.
688      * Subclasses of <tt>ClassLoader</tt> need not usually invoke this method,
689      * because most class loaders need to override just {@link
690      * #findClass(String)}.  </p>
691      *
692      * @param  name
693      *         The <a href="#name">binary name</a> of the class
694      *
695      * @return  The <tt>Class</tt> object for the specified <tt>name</tt>
696      *
697      * @throws  ClassNotFoundException
698      *          If the class could not be found
699      *
700      * @see  #ClassLoader(ClassLoader)
701      * @see  #getParent()
702      */
findSystemClass(String name)703     protected final Class<?> findSystemClass(String name)
704         throws ClassNotFoundException
705     {
706         return Class.forName(name, false, getSystemClassLoader());
707     }
708 
709     /**
710      * Returns a class loaded by the bootstrap class loader;
711      * or return null if not found.
712      */
findBootstrapClassOrNull(String name)713     private Class<?> findBootstrapClassOrNull(String name)
714     {
715         return null;
716     }
717 
718     /**
719      * Returns the class with the given <a href="#name">binary name</a> if this
720      * loader has been recorded by the Java virtual machine as an initiating
721      * loader of a class with that <a href="#name">binary name</a>.  Otherwise
722      * <tt>null</tt> is returned.
723      *
724      * @param  name
725      *         The <a href="#name">binary name</a> of the class
726      *
727      * @return  The <tt>Class</tt> object, or <tt>null</tt> if the class has
728      *          not been loaded
729      *
730      * @since  1.1
731      */
findLoadedClass(String name)732     protected final Class<?> findLoadedClass(String name) {
733         ClassLoader loader;
734         if (this == BootClassLoader.getInstance())
735             loader = null;
736         else
737             loader = this;
738         return VMClassLoader.findLoadedClass(loader, name);
739     }
740 
741     /**
742      * Sets the signers of a class.  This should be invoked after defining a
743      * class.
744      *
745      * @param  c
746      *         The <tt>Class</tt> object
747      *
748      * @param  signers
749      *         The signers for the class
750      *
751      * @since  1.1
752      */
setSigners(Class<?> c, Object[] signers)753     protected final void setSigners(Class<?> c, Object[] signers) {
754     }
755 
756 
757     // -- Resource --
758 
759     /**
760      * Finds the resource with the given name.  A resource is some data
761      * (images, audio, text, etc) that can be accessed by class code in a way
762      * that is independent of the location of the code.
763      *
764      * <p> The name of a resource is a '<tt>/</tt>'-separated path name that
765      * identifies the resource.
766      *
767      * <p> This method will first search the parent class loader for the
768      * resource; if the parent is <tt>null</tt> the path of the class loader
769      * built-in to the virtual machine is searched.  That failing, this method
770      * will invoke {@link #findResource(String)} to find the resource.  </p>
771      *
772      * @apiNote When overriding this method it is recommended that an
773      * implementation ensures that any delegation is consistent with the {@link
774      * #getResources(java.lang.String) getResources(String)} method.
775      *
776      * @param  name
777      *         The resource name
778      *
779      * @return  A <tt>URL</tt> object for reading the resource, or
780      *          <tt>null</tt> if the resource could not be found or the invoker
781      *          doesn't have adequate  privileges to get the resource.
782      *
783      * @since  1.1
784      */
getResource(String name)785     public URL getResource(String name) {
786         URL url;
787         if (parent != null) {
788             url = parent.getResource(name);
789         } else {
790             url = getBootstrapResource(name);
791         }
792         if (url == null) {
793             url = findResource(name);
794         }
795         return url;
796     }
797 
798     /**
799      * Finds all the resources with the given name. A resource is some data
800      * (images, audio, text, etc) that can be accessed by class code in a way
801      * that is independent of the location of the code.
802      *
803      * <p>The name of a resource is a <tt>/</tt>-separated path name that
804      * identifies the resource.
805      *
806      * <p> The search order is described in the documentation for {@link
807      * #getResource(String)}.  </p>
808      *
809      * @apiNote When overriding this method it is recommended that an
810      * implementation ensures that any delegation is consistent with the {@link
811      * #getResource(java.lang.String) getResource(String)} method. This should
812      * ensure that the first element returned by the Enumeration's
813      * {@code nextElement} method is the same resource that the
814      * {@code getResource(String)} method would return.
815      *
816      * @param  name
817      *         The resource name
818      *
819      * @return  An enumeration of {@link java.net.URL <tt>URL</tt>} objects for
820      *          the resource.  If no resources could  be found, the enumeration
821      *          will be empty.  Resources that the class loader doesn't have
822      *          access to will not be in the enumeration.
823      *
824      * @throws  IOException
825      *          If I/O errors occur
826      *
827      * @see  #findResources(String)
828      *
829      * @since  1.2
830      */
getResources(String name)831     public Enumeration<URL> getResources(String name) throws IOException {
832         @SuppressWarnings("unchecked")
833         Enumeration<URL>[] tmp = (Enumeration<URL>[]) new Enumeration<?>[2];
834         if (parent != null) {
835             tmp[0] = parent.getResources(name);
836         } else {
837             tmp[0] = getBootstrapResources(name);
838         }
839         tmp[1] = findResources(name);
840 
841         return new CompoundEnumeration<>(tmp);
842     }
843 
844     /**
845      * Finds the resource with the given name. Class loader implementations
846      * should override this method to specify where to find resources.
847      *
848      * @param  name
849      *         The resource name
850      *
851      * @return  A <tt>URL</tt> object for reading the resource, or
852      *          <tt>null</tt> if the resource could not be found
853      *
854      * @since  1.2
855      */
findResource(String name)856     protected URL findResource(String name) {
857         return null;
858     }
859 
860     /**
861      * Returns an enumeration of {@link java.net.URL <tt>URL</tt>} objects
862      * representing all the resources with the given name. Class loader
863      * implementations should override this method to specify where to load
864      * resources from.
865      *
866      * @param  name
867      *         The resource name
868      *
869      * @return  An enumeration of {@link java.net.URL <tt>URL</tt>} objects for
870      *          the resources
871      *
872      * @throws  IOException
873      *          If I/O errors occur
874      *
875      * @since  1.2
876      */
findResources(String name)877     protected Enumeration<URL> findResources(String name) throws IOException {
878         return java.util.Collections.emptyEnumeration();
879     }
880 
881     /**
882      * Registers the caller as parallel capable.
883      * The registration succeeds if and only if all of the following
884      * conditions are met:
885      * <ol>
886      * <li> no instance of the caller has been created</li>
887      * <li> all of the super classes (except class Object) of the caller are
888      * registered as parallel capable</li>
889      * </ol>
890      * <p>Note that once a class loader is registered as parallel capable, there
891      * is no way to change it back.</p>
892      *
893      * @return  true if the caller is successfully registered as
894      *          parallel capable and false if otherwise.
895      *
896      * @since   1.7
897      */
898     @CallerSensitive
registerAsParallelCapable()899     protected static boolean registerAsParallelCapable() {
900         return true;
901     }
902 
903     /**
904      * Find a resource of the specified name from the search path used to load
905      * classes.  This method locates the resource through the system class
906      * loader (see {@link #getSystemClassLoader()}).
907      *
908      * @param  name
909      *         The resource name
910      *
911      * @return  A {@link java.net.URL <tt>URL</tt>} object for reading the
912      *          resource, or <tt>null</tt> if the resource could not be found
913      *
914      * @since  1.1
915      */
getSystemResource(String name)916     public static URL getSystemResource(String name) {
917         ClassLoader system = getSystemClassLoader();
918         if (system == null) {
919             return getBootstrapResource(name);
920         }
921         return system.getResource(name);
922     }
923 
924     /**
925      * Finds all resources of the specified name from the search path used to
926      * load classes.  The resources thus found are returned as an
927      * {@link java.util.Enumeration <tt>Enumeration</tt>} of {@link
928      * java.net.URL <tt>URL</tt>} objects.
929      *
930      * <p> The search order is described in the documentation for {@link
931      * #getSystemResource(String)}.  </p>
932      *
933      * @param  name
934      *         The resource name
935      *
936      * @return  An enumeration of resource {@link java.net.URL <tt>URL</tt>}
937      *          objects
938      *
939      * @throws  IOException
940      *          If I/O errors occur
941 
942      * @since  1.2
943      */
getSystemResources(String name)944     public static Enumeration<URL> getSystemResources(String name)
945         throws IOException
946     {
947         ClassLoader system = getSystemClassLoader();
948         if (system == null) {
949             return getBootstrapResources(name);
950         }
951         return system.getResources(name);
952     }
953 
954     /**
955      * Find resources from the VM's built-in classloader.
956      */
getBootstrapResource(String name)957     private static URL getBootstrapResource(String name) {
958         return null;
959     }
960 
961     /**
962      * Find resources from the VM's built-in classloader.
963      */
getBootstrapResources(String name)964     private static Enumeration<URL> getBootstrapResources(String name)
965         throws IOException
966     {
967         return null;
968     }
969 
970 
971 
972     /**
973      * Returns an input stream for reading the specified resource.
974      *
975      * <p> The search order is described in the documentation for {@link
976      * #getResource(String)}.  </p>
977      *
978      * @param  name
979      *         The resource name
980      *
981      * @return  An input stream for reading the resource, or <tt>null</tt>
982      *          if the resource could not be found
983      *
984      * @since  1.1
985      */
getResourceAsStream(String name)986     public InputStream getResourceAsStream(String name) {
987         URL url = getResource(name);
988         try {
989             return url != null ? url.openStream() : null;
990         } catch (IOException e) {
991             return null;
992         }
993     }
994 
995     /**
996      * Open for reading, a resource of the specified name from the search path
997      * used to load classes.  This method locates the resource through the
998      * system class loader (see {@link #getSystemClassLoader()}).
999      *
1000      * @param  name
1001      *         The resource name
1002      *
1003      * @return  An input stream for reading the resource, or <tt>null</tt>
1004      *          if the resource could not be found
1005      *
1006      * @since  1.1
1007      */
getSystemResourceAsStream(String name)1008     public static InputStream getSystemResourceAsStream(String name) {
1009         URL url = getSystemResource(name);
1010         try {
1011             return url != null ? url.openStream() : null;
1012         } catch (IOException e) {
1013             return null;
1014         }
1015     }
1016 
1017 
1018     // -- Hierarchy --
1019 
1020     /**
1021      * Returns the parent class loader for delegation. Some implementations may
1022      * use <tt>null</tt> to represent the bootstrap class loader. This method
1023      * will return <tt>null</tt> in such implementations if this class loader's
1024      * parent is the bootstrap class loader.
1025      *
1026      * <p> If a security manager is present, and the invoker's class loader is
1027      * not <tt>null</tt> and is not an ancestor of this class loader, then this
1028      * method invokes the security manager's {@link
1029      * SecurityManager#checkPermission(java.security.Permission)
1030      * <tt>checkPermission</tt>} method with a {@link
1031      * RuntimePermission#RuntimePermission(String)
1032      * <tt>RuntimePermission("getClassLoader")</tt>} permission to verify
1033      * access to the parent class loader is permitted.  If not, a
1034      * <tt>SecurityException</tt> will be thrown.  </p>
1035      *
1036      * @return  The parent <tt>ClassLoader</tt>
1037      *
1038      * @throws  SecurityException
1039      *          If a security manager exists and its <tt>checkPermission</tt>
1040      *          method doesn't allow access to this class loader's parent class
1041      *          loader.
1042      *
1043      * @since  1.2
1044      */
1045     @CallerSensitive
getParent()1046     public final ClassLoader getParent() {
1047         return parent;
1048     }
1049 
1050     // Android-changed: Removed "java.system.class.loader" paragraph.
1051     /**
1052      * Returns the system class loader for delegation.  This is the default
1053      * delegation parent for new <tt>ClassLoader</tt> instances, and is
1054      * typically the class loader used to start the application.
1055      *
1056      * <p> This method is first invoked early in the runtime's startup
1057      * sequence, at which point it creates the system class loader and sets it
1058      * as the context class loader of the invoking <tt>Thread</tt>.
1059      *
1060      * <p> The default system class loader is an implementation-dependent
1061      * instance of this class.
1062      *
1063      * <p> If a security manager is present, and the invoker's class loader is
1064      * not <tt>null</tt> and the invoker's class loader is not the same as or
1065      * an ancestor of the system class loader, then this method invokes the
1066      * security manager's {@link
1067      * SecurityManager#checkPermission(java.security.Permission)
1068      * <tt>checkPermission</tt>} method with a {@link
1069      * RuntimePermission#RuntimePermission(String)
1070      * <tt>RuntimePermission("getClassLoader")</tt>} permission to verify
1071      * access to the system class loader.  If not, a
1072      * <tt>SecurityException</tt> will be thrown.  </p>
1073      *
1074      * @return  The system <tt>ClassLoader</tt> for delegation, or
1075      *          <tt>null</tt> if none
1076      *
1077      * @throws  SecurityException
1078      *          If a security manager exists and its <tt>checkPermission</tt>
1079      *          method doesn't allow access to the system class loader.
1080      *
1081      * @throws  IllegalStateException
1082      *          If invoked recursively during the construction of the class
1083      *          loader specified by the "<tt>java.system.class.loader</tt>"
1084      *          property.
1085      *
1086      * @throws  Error
1087      *          If the system property "<tt>java.system.class.loader</tt>"
1088      *          is defined but the named class could not be loaded, the
1089      *          provider class does not define the required constructor, or an
1090      *          exception is thrown by that constructor when it is invoked. The
1091      *          underlying cause of the error can be retrieved via the
1092      *          {@link Throwable#getCause()} method.
1093      *
1094      * @revised  1.4
1095      */
1096     @CallerSensitive
getSystemClassLoader()1097     public static ClassLoader getSystemClassLoader() {
1098         return SystemClassLoader.loader;
1099     }
1100 
1101     // Returns the class's class loader, or null if none.
getClassLoader(Class<?> caller)1102     static ClassLoader getClassLoader(Class<?> caller) {
1103         // This can be null if the VM is requesting it
1104         if (caller == null) {
1105             return null;
1106         }
1107         // Android-changed: Use Class.getClassLoader(); there is no Class.getClassLoader0().
1108         // // Circumvent security check since this is package-private
1109         // return caller.getClassLoader0();
1110         return caller.getClassLoader();
1111     }
1112 
1113     // -- Package --
1114 
1115     /**
1116      * Defines a package by name in this <tt>ClassLoader</tt>.  This allows
1117      * class loaders to define the packages for their classes. Packages must
1118      * be created before the class is defined, and package names must be
1119      * unique within a class loader and cannot be redefined or changed once
1120      * created.
1121      *
1122      * @param  name
1123      *         The package name
1124      *
1125      * @param  specTitle
1126      *         The specification title
1127      *
1128      * @param  specVersion
1129      *         The specification version
1130      *
1131      * @param  specVendor
1132      *         The specification vendor
1133      *
1134      * @param  implTitle
1135      *         The implementation title
1136      *
1137      * @param  implVersion
1138      *         The implementation version
1139      *
1140      * @param  implVendor
1141      *         The implementation vendor
1142      *
1143      * @param  sealBase
1144      *         If not <tt>null</tt>, then this package is sealed with
1145      *         respect to the given code source {@link java.net.URL
1146      *         <tt>URL</tt>}  object.  Otherwise, the package is not sealed.
1147      *
1148      * @return  The newly defined <tt>Package</tt> object
1149      *
1150      * @throws  IllegalArgumentException
1151      *          If package name duplicates an existing package either in this
1152      *          class loader or one of its ancestors
1153      *
1154      * @since  1.2
1155      */
definePackage(String name, String specTitle, String specVersion, String specVendor, String implTitle, String implVersion, String implVendor, URL sealBase)1156     protected Package definePackage(String name, String specTitle,
1157                                     String specVersion, String specVendor,
1158                                     String implTitle, String implVersion,
1159                                     String implVendor, URL sealBase)
1160         throws IllegalArgumentException
1161     {
1162         synchronized (packages) {
1163             Package pkg = packages.get(name);
1164             if (pkg != null) {
1165                 throw new IllegalArgumentException(name);
1166             }
1167             pkg = new Package(name, specTitle, specVersion, specVendor,
1168                               implTitle, implVersion, implVendor,
1169                               sealBase, this);
1170             packages.put(name, pkg);
1171             return pkg;
1172         }
1173     }
1174 
1175     /**
1176      * Returns a <tt>Package</tt> that has been defined by this class loader
1177      * or any of its ancestors.
1178      *
1179      * @param  name
1180      *         The package name
1181      *
1182      * @return  The <tt>Package</tt> corresponding to the given name, or
1183      *          <tt>null</tt> if not found
1184      *
1185      * @since  1.2
1186      */
getPackage(String name)1187     protected Package getPackage(String name) {
1188         Package pkg;
1189         synchronized (packages) {
1190             pkg = packages.get(name);
1191         }
1192         return pkg;
1193     }
1194 
1195     /**
1196      * Returns all of the <tt>Packages</tt> defined by this class loader and
1197      * its ancestors.
1198      *
1199      * @return  The array of <tt>Package</tt> objects defined by this
1200      *          <tt>ClassLoader</tt>
1201      *
1202      * @since  1.2
1203      */
getPackages()1204     protected Package[] getPackages() {
1205         Map<String, Package> map;
1206         synchronized (packages) {
1207             map = new HashMap<>(packages);
1208         }
1209         Package[] pkgs;
1210         return map.values().toArray(new Package[map.size()]);
1211     }
1212 
1213 
1214     // -- Native library access --
1215 
1216     /**
1217      * Returns the absolute path name of a native library.  The VM invokes this
1218      * method to locate the native libraries that belong to classes loaded with
1219      * this class loader. If this method returns <tt>null</tt>, the VM
1220      * searches the library along the path specified as the
1221      * "<tt>java.library.path</tt>" property.
1222      *
1223      * @param  libname
1224      *         The library name
1225      *
1226      * @return  The absolute path of the native library
1227      *
1228      * @see  System#loadLibrary(String)
1229      * @see  System#mapLibraryName(String)
1230      *
1231      * @since  1.2
1232      */
findLibrary(String libname)1233     protected String findLibrary(String libname) {
1234         return null;
1235     }
1236 
1237     /**
1238      * Sets the default assertion status for this class loader.  This setting
1239      * determines whether classes loaded by this class loader and initialized
1240      * in the future will have assertions enabled or disabled by default.
1241      * This setting may be overridden on a per-package or per-class basis by
1242      * invoking {@link #setPackageAssertionStatus(String, boolean)} or {@link
1243      * #setClassAssertionStatus(String, boolean)}.
1244      *
1245      * @param  enabled
1246      *         <tt>true</tt> if classes loaded by this class loader will
1247      *         henceforth have assertions enabled by default, <tt>false</tt>
1248      *         if they will have assertions disabled by default.
1249      *
1250      * @since  1.4
1251      */
setDefaultAssertionStatus(boolean enabled)1252     public void setDefaultAssertionStatus(boolean enabled) {
1253     }
1254 
1255     /**
1256      * Sets the package default assertion status for the named package.  The
1257      * package default assertion status determines the assertion status for
1258      * classes initialized in the future that belong to the named package or
1259      * any of its "subpackages".
1260      *
1261      * <p> A subpackage of a package named p is any package whose name begins
1262      * with "<tt>p.</tt>".  For example, <tt>javax.swing.text</tt> is a
1263      * subpackage of <tt>javax.swing</tt>, and both <tt>java.util</tt> and
1264      * <tt>java.lang.reflect</tt> are subpackages of <tt>java</tt>.
1265      *
1266      * <p> In the event that multiple package defaults apply to a given class,
1267      * the package default pertaining to the most specific package takes
1268      * precedence over the others.  For example, if <tt>javax.lang</tt> and
1269      * <tt>javax.lang.reflect</tt> both have package defaults associated with
1270      * them, the latter package default applies to classes in
1271      * <tt>javax.lang.reflect</tt>.
1272      *
1273      * <p> Package defaults take precedence over the class loader's default
1274      * assertion status, and may be overridden on a per-class basis by invoking
1275      * {@link #setClassAssertionStatus(String, boolean)}.  </p>
1276      *
1277      * @param  packageName
1278      *         The name of the package whose package default assertion status
1279      *         is to be set. A <tt>null</tt> value indicates the unnamed
1280      *         package that is "current"
1281      *         (see section 7.4.2 of
1282      *         <cite>The Java&trade; Language Specification</cite>.)
1283      *
1284      * @param  enabled
1285      *         <tt>true</tt> if classes loaded by this classloader and
1286      *         belonging to the named package or any of its subpackages will
1287      *         have assertions enabled by default, <tt>false</tt> if they will
1288      *         have assertions disabled by default.
1289      *
1290      * @since  1.4
1291      */
setPackageAssertionStatus(String packageName, boolean enabled)1292     public void setPackageAssertionStatus(String packageName,
1293                                           boolean enabled) {
1294     }
1295 
1296     /**
1297      * Sets the desired assertion status for the named top-level class in this
1298      * class loader and any nested classes contained therein.  This setting
1299      * takes precedence over the class loader's default assertion status, and
1300      * over any applicable per-package default.  This method has no effect if
1301      * the named class has already been initialized.  (Once a class is
1302      * initialized, its assertion status cannot change.)
1303      *
1304      * <p> If the named class is not a top-level class, this invocation will
1305      * have no effect on the actual assertion status of any class. </p>
1306      *
1307      * @param  className
1308      *         The fully qualified class name of the top-level class whose
1309      *         assertion status is to be set.
1310      *
1311      * @param  enabled
1312      *         <tt>true</tt> if the named class is to have assertions
1313      *         enabled when (and if) it is initialized, <tt>false</tt> if the
1314      *         class is to have assertions disabled.
1315      *
1316      * @since  1.4
1317      */
setClassAssertionStatus(String className, boolean enabled)1318     public void setClassAssertionStatus(String className, boolean enabled) {
1319     }
1320 
1321     /**
1322      * Sets the default assertion status for this class loader to
1323      * <tt>false</tt> and discards any package defaults or class assertion
1324      * status settings associated with the class loader.  This method is
1325      * provided so that class loaders can be made to ignore any command line or
1326      * persistent assertion status settings and "start with a clean slate."
1327      *
1328      * @since  1.4
1329      */
clearAssertionStatus()1330     public void clearAssertionStatus() {
1331         /*
1332          * Whether or not "Java assertion maps" are initialized, set
1333          * them to empty maps, effectively ignoring any present settings.
1334          */
1335     }
1336 }
1337 
1338 
1339 class BootClassLoader extends ClassLoader {
1340 
1341     private static BootClassLoader instance;
1342 
1343     @FindBugsSuppressWarnings("DP_CREATE_CLASSLOADER_INSIDE_DO_PRIVILEGED")
getInstance()1344     public static synchronized BootClassLoader getInstance() {
1345         if (instance == null) {
1346             instance = new BootClassLoader();
1347         }
1348 
1349         return instance;
1350     }
1351 
BootClassLoader()1352     public BootClassLoader() {
1353         super(null);
1354     }
1355 
1356     @Override
findClass(String name)1357     protected Class<?> findClass(String name) throws ClassNotFoundException {
1358         return Class.classForName(name, false, null);
1359     }
1360 
1361     @Override
findResource(String name)1362     protected URL findResource(String name) {
1363         return VMClassLoader.getResource(name);
1364     }
1365 
1366     @SuppressWarnings("unused")
1367     @Override
findResources(String resName)1368     protected Enumeration<URL> findResources(String resName) throws IOException {
1369         return Collections.enumeration(VMClassLoader.getResources(resName));
1370     }
1371 
1372     /**
1373      * Returns package information for the given package. Unfortunately, the
1374      * Android BootClassLoader doesn't really have this information, and as a
1375      * non-secure ClassLoader, it isn't even required to, according to the spec.
1376      * Yet, we want to provide it, in order to make all those hopeful callers of
1377      * {@code myClass.getPackage().getName()} happy. Thus we construct a Package
1378      * object the first time it is being requested and fill most of the fields
1379      * with dummy values. The Package object is then put into the ClassLoader's
1380      * Package cache, so we see the same one next time. We don't create Package
1381      * objects for null arguments or for the default package.
1382      * <p>
1383      * There a limited chance that we end up with multiple Package objects
1384      * representing the same package: It can happen when when a package is
1385      * scattered across different JAR files being loaded by different
1386      * ClassLoaders. Rather unlikely, and given that this whole thing is more or
1387      * less a workaround, probably not worth the effort.
1388      */
1389     @Override
getPackage(String name)1390     protected Package getPackage(String name) {
1391         if (name != null && !name.isEmpty()) {
1392             synchronized (this) {
1393                 Package pack = super.getPackage(name);
1394 
1395                 if (pack == null) {
1396                     pack = definePackage(name, "Unknown", "0.0", "Unknown", "Unknown", "0.0",
1397                             "Unknown", null);
1398                 }
1399 
1400                 return pack;
1401             }
1402         }
1403 
1404         return null;
1405     }
1406 
1407     @Override
getResource(String resName)1408     public URL getResource(String resName) {
1409         return findResource(resName);
1410     }
1411 
1412     @Override
loadClass(String className, boolean resolve)1413     protected Class<?> loadClass(String className, boolean resolve)
1414            throws ClassNotFoundException {
1415         Class<?> clazz = findLoadedClass(className);
1416 
1417         if (clazz == null) {
1418             clazz = findClass(className);
1419         }
1420 
1421         return clazz;
1422     }
1423 
1424     @Override
getResources(String resName)1425     public Enumeration<URL> getResources(String resName) throws IOException {
1426         return findResources(resName);
1427     }
1428 }
1429