最近找工作,面试网易和微策略,都问到了ClassLoader这个东西,看来应该是比较重要的,所以在这总结一下,嗯,类源码有点长,慢慢看吧。

翻译一下,不当之处欢迎指正。

  1. /**
  2. * A class loader is an object that is responsible for loading classes. The 翻译:ClassLoader是一个用于加载类的对象。它是一个抽象类。
  3. * class <tt>ClassLoader</tt> is an abstract class. Given the <a              给出一个类的二进制名称,它能够定位并且产生用于构造类的数据。
  4. * href="#name">binary name</a> of a class, a class loader should attempt to       一个典型的策略就是将名称转换为文件名,然后从文件系统中读取类文件。
  5. * locate or generate data that constitutes a definition for the class. A
  6. * typical strategy is to transform the name into a file name and then read a
  7. * "class file" of that name from a file system.
  8. *
  9. * <p> Every {@link Class <tt>Class</tt>} object contains a {@link             每个对象都包含了一个相应类加载器的引用,可以通过getClassLoader()
  10. * Class#getClassLoader() reference} to the <tt>ClassLoader</tt> that defined 获取这个引用。
  11. * it.
  12. *
  13. * <p> <tt>Class</tt> objects for array classes are not created by class 数组类的类对象不是类加载器创造的,而是java运行时要求自动创造的。
  14. * loaders, but are created automatically as required by the Java runtime.        数组类的类加载器,和它的元素类型的类加载器一样,通过getClassLoader()
  15. * The class loader for an array class, as returned by {@link                返回;如果元素类型是一个泛型,那么这个数组类就没有类加载器。
  16. * Class#getClassLoader()} is the same as the class loader for its element
  17. * type; if the element type is a primitive type, then the array class has no
  18. * class loader.
  19. *
  20. * <p> Applications implement subclasses of <tt>ClassLoader</tt> in order to 实现了ClassLoader子类的应用是为了扩展一些行为,这些行为
  21. * extend the manner in which the Java virtual machine dynamically loads 能够使java虚拟机动态加载类。
  22. * classes.
  23. *
  24. * <p> Class loaders may typically be used by security managers to indicate 类加载器经常被用来安全领域的安全管理。(这地方翻译不够精确,使用*号mark一下,
  25. * security domains.                                        后面使用*缘由与此处相同)
  26. *
  27. * <p> The <tt>ClassLoader</tt> class uses a delegation model to search for ClassLoader使用了一个代理模型来寻找类和资源。
  28. * classes and resources. Each instance of <tt>ClassLoader</tt> has an          每个ClassLoader的实例都有一个相关的父类加载器。
  29. * associated parent class loader. When requested to find a class or           当要求找到一个类或者资源的时候,ClassLoader的实例将会使用代理先寻找父类的类和资源,
  30. * resource, a <tt>ClassLoader</tt> instance will delegate the search for the 然后找到这个类本身的类和资源。java虚拟机内嵌的类加载器,被称作
  31. * class or resource to its parent class loader before attempting to find the 类加载器引导程序,虽然它本身没有父类但是它可能会充当某一个类加载器实例的父类。(*)
  32. * class or resource itself. The virtual machine's built-in class loader,
  33. * called the "bootstrap class loader", does not itself have a parent but may
  34. * serve as the parent of a <tt>ClassLoader</tt> instance.
  35. *
  36. * <p> Class loaders that support concurrent loading of classes are known as       支持并发式加载类的类加载器最广为人知的是,类加载器的并行能力和要求
  37. * <em>parallel capable</em> class loaders and are required to register 在它们的类初始化的时候,通过调用registerAsParallelCapable()方法来注册类加载器本身。
  38. * themselves at their class initialization time by invoking the
  39. * {@link
  40. * #registerAsParallelCapable <tt>ClassLoader.registerAsParallelCapable</tt>}
  41. * method. Note that the <tt>ClassLoader</tt> class is registered as parallel 需要注意的是ClassLoader这个类默认被注册为拥有并发能力。
  42. * capable by default. However, its subclasses still need to register themselves 然而,如果要保证ClassLoader的子类具有并发能力的话仍然需要注册它们
  43. * if they are parallel capable. <br>                              本身。
  44. * In environments in which the delegation model is not strictly 在代理模式不是严格分级的环境下,
  45. * hierarchical, class loaders need to be parallel capable, otherwise class 类加载器需要具有并发能力,否则类加载可能会造成死锁,
  46. * loading can lead to deadlocks because the loader lock is held for the 因为loader lock在类加载过程期间一直被持有。
  47. * duration of the class loading process (see {@link #loadClass
  48. * <tt>loadClass</tt>} methods).
  49. *
  50. * <p> Normally, the Java virtual machine loads classes from the local file       通常的话,java虚拟机以一种平台相关的方式从本地文件系统
  51. * system in a platform-dependent manner. For example, on UNIX systems, the 中加载类。例如,在unix系统上,虚拟机将会从CLSSPATH环境变量
  52. * virtual machine loads classes from the directory defined by the 定义的目录下加载类。
  53. * <tt>CLASSPATH</tt> environment variable.
  54. *
  55. * <p> However, some classes may not originate from a file; they may originate 然而,一些类可能原本不是来自文件;它们可能来自于
  56. * from other sources, such as the network, or they could be constructed by an 其它的一些资源,例如网络,或者它们能够通过一个应用来构造。
  57. * application. The method {@link #defineClass(String, byte[], int, int) defineClass(String ,byte[],int,int)方法将一个数组的字节
  58. * <tt>defineClass</tt>} converts an array of bytes into an instance of class 转换成一个类的实例。这个新的类实例可以使用newInstance()方法来创建。
  59. * <tt>Class</tt>. Instances of this newly defined class can be created using
  60. * {@link Class#newInstance <tt>Class.newInstance</tt>}.
  61. *
  62. * <p> The methods and constructors of objects created by a class loader may 对象的方法和构造器通过类加载器来创建,可能会涉及到其它的类。
  63. * reference other classes. To determine the class(es) referred to, the Java 为了确定所涉及到的类,java虚拟机调用原本创建类的类加载器的loadclass()
  64. * virtual machine invokes the {@link #loadClass <tt>loadClass</tt>} method of 方法。
  65. * the class loader that originally created the class.
  66. *
  67. * <p> For example, an application could create a network class loader to 例如,一个应用可能会创建一个网络类加载器来从服务器上下载类文件。
  68. * download class files from a server. Sample code might look like: 样例代码像这样子:
  69. *
  70. * <blockquote><pre>
  71. * ClassLoader loader = new NetworkClassLoader(host, port);
  72. * Object main = loader.loadClass("Main", true).newInstance();
  73. *  . . .
  74. * </pre></blockquote>
  75. *
  76. * <p> The network class loader subclass must define the methods {@link 这个网络类加载器的子类必须定义findClass()方法
  77. * #findClass <tt>findClass</tt>} and <tt>loadClassData</tt> to load a class 和loadClassData()方法用来从网络中加载类。
  78. * from the network. Once it has downloaded the bytes that make up the class, 一旦它下载完了组成类的字节,它就会使用defineClass()
  79. * it should use the method {@link #defineClass <tt>defineClass</tt>} to 方法来创建一个类的实例。一个简单的实现是:
  80. * create a class instance. A sample implementation is:
  81. *
  82. * <blockquote><pre>
  83. * class NetworkClassLoader extends ClassLoader {
  84. * String host;
  85. * int port;
  86. *
  87. * public Class findClass(String name) {
  88. * byte[] b = loadClassData(name);
  89. * return defineClass(name, b, 0, b.length);
  90. * }
  91. *
  92. * private byte[] loadClassData(String name) {
  93. * // load the class data from the connection
  94. *  . . .
  95. * }
  96. * }
  97. * </pre></blockquote>
  98. *
  99. * <h3> <a name="name">Binary names</a> </h3>
  100. *
  101. * <p> Any class name provided as a {@link String} parameter to methods in
  102. * <tt>ClassLoader</tt> must be a binary name as defined by
  103. * <cite>The Java™ Language Specification</cite>.
  104. *
  105. * <p> Examples of valid class names include:
  106. * <blockquote><pre>
  107. * "java.lang.String"
  108. * "javax.swing.JSpinner$DefaultEditor"
  109. * "java.security.KeyStore$Builder$FileBuilder$1"
  110. * "java.net.URLClassLoader$3$1"
  111. * </pre></blockquote>
  112. *
  113. * @see #resolveClass(Class)
  114. * @since 1.0
  115. */
  116. public abstract class ClassLoader {
  117.  
  118. private static native void registerNatives();
  119. static {
  120. registerNatives();
  121. }
  122.  
  123. // The parent class loader for delegation
  124. // Note: VM hardcoded the offset of this field, thus all new fields
  125. // must be added *after* it.
  126. private final ClassLoader parent;
  127.  
  128. /**
  129. * Encapsulates the set of parallel capable loader types.
  130. */
  131. private static class ParallelLoaders {
  132. private ParallelLoaders() {}
  133.  
  134. // the set of parallel capable loader types
  135. private static final Set<Class<? extends ClassLoader>> loaderTypes =
  136. Collections.newSetFromMap(
  137. new WeakHashMap<Class<? extends ClassLoader>, Boolean>());
  138. static {
  139. synchronized (loaderTypes) { loaderTypes.add(ClassLoader.class); }
  140. }
  141.  
  142. /**
  143. * Registers the given class loader type as parallel capabale.
  144. * Returns {@code true} is successfully registered; {@code false} if
  145. * loader's super class is not registered.
  146. */
  147. static boolean register(Class<? extends ClassLoader> c) {
  148. synchronized (loaderTypes) {
  149. if (loaderTypes.contains(c.getSuperclass())) {
  150. // register the class loader as parallel capable
  151. // if and only if all of its super classes are.
  152. // Note: given current classloading sequence, if
  153. // the immediate super class is parallel capable,
  154. // all the super classes higher up must be too.
  155. loaderTypes.add(c);
  156. return true;
  157. } else {
  158. return false;
  159. }
  160. }
  161. }
  162.  
  163. /**
  164. * Returns {@code true} if the given class loader type is
  165. * registered as parallel capable.
  166. */
  167. static boolean isRegistered(Class<? extends ClassLoader> c) {
  168. synchronized (loaderTypes) {
  169. return loaderTypes.contains(c);
  170. }
  171. }
  172. }
  173.  
  174. // Maps class name to the corresponding lock object when the current
  175. // class loader is parallel capable.
  176. // Note: VM also uses this field to decide if the current class loader
  177. // is parallel capable and the appropriate lock object for class loading.
  178. private final ConcurrentHashMap<String, Object> parallelLockMap;
  179.  
  180. // Hashtable that maps packages to certs
  181. private final Map <String, Certificate[]> package2certs;
  182.  
  183. // Shared among all packages with unsigned classes
  184. private static final Certificate[] nocerts = new Certificate[0];
  185.  
  186. // The classes loaded by this class loader. The only purpose of this table
  187. // is to keep the classes from being GC'ed until the loader is GC'ed.
  188. private final Vector<Class<?>> classes = new Vector<>();
  189.  
  190. // The "default" domain. Set as the default ProtectionDomain on newly
  191. // created classes.
  192. private final ProtectionDomain defaultDomain =
  193. new ProtectionDomain(new CodeSource(null, (Certificate[]) null),
  194. null, this, null);
  195.  
  196. // The initiating protection domains for all classes loaded by this loader
  197. private final Set<ProtectionDomain> domains;
  198.  
  199. // Invoked by the VM to record every loaded class with this loader.
  200. void addClass(Class<?> c) {
  201. classes.addElement(c);
  202. }
  203.  
  204. // The packages defined in this class loader. Each package name is mapped
  205. // to its corresponding Package object.
  206. // @GuardedBy("itself")
  207. private final HashMap<String, Package> packages = new HashMap<>();
  208.  
  209. private static Void checkCreateClassLoader() {
  210. SecurityManager security = System.getSecurityManager();
  211. if (security != null) {
  212. security.checkCreateClassLoader();
  213. }
  214. return null;
  215. }
  216.  
  217. private ClassLoader(Void unused, ClassLoader parent) {
  218. this.parent = parent;
  219. if (ParallelLoaders.isRegistered(this.getClass())) {
  220. parallelLockMap = new ConcurrentHashMap<>();
  221. package2certs = new ConcurrentHashMap<>();
  222. domains =
  223. Collections.synchronizedSet(new HashSet<ProtectionDomain>());
  224. assertionLock = new Object();
  225. } else {
  226. // no finer-grained lock; lock on the classloader instance
  227. parallelLockMap = null;
  228. package2certs = new Hashtable<>();
  229. domains = new HashSet<>();
  230. assertionLock = this;
  231. }
  232. }
  233.  
  234. /**
  235. * Creates a new class loader using the specified parent class loader for
  236. * delegation.
  237. *
  238. * <p> If there is a security manager, its {@link
  239. * SecurityManager#checkCreateClassLoader()
  240. * <tt>checkCreateClassLoader</tt>} method is invoked. This may result in
  241. * a security exception. </p>
  242. *
  243. * @param parent
  244. * The parent class loader
  245. *
  246. * @throws SecurityException
  247. * If a security manager exists and its
  248. * <tt>checkCreateClassLoader</tt> method doesn't allow creation
  249. * of a new class loader.
  250. *
  251. * @since 1.2
  252. */
  253. protected ClassLoader(ClassLoader parent) {
  254. this(checkCreateClassLoader(), parent);
  255. }
  256.  
  257. /**
  258. * Creates a new class loader using the <tt>ClassLoader</tt> returned by
  259. * the method {@link #getSystemClassLoader()
  260. * <tt>getSystemClassLoader()</tt>} as the parent class loader.
  261. *
  262. * <p> If there is a security manager, its {@link
  263. * SecurityManager#checkCreateClassLoader()
  264. * <tt>checkCreateClassLoader</tt>} method is invoked. This may result in
  265. * a security exception. </p>
  266. *
  267. * @throws SecurityException
  268. * If a security manager exists and its
  269. * <tt>checkCreateClassLoader</tt> method doesn't allow creation
  270. * of a new class loader.
  271. */
  272. protected ClassLoader() {
  273. this(checkCreateClassLoader(), getSystemClassLoader());
  274. }
  275.  
  276. // -- Class --
  277.  
  278. /**
  279. * Loads the class with the specified <a href="#name">binary name</a>.
  280. * This method searches for classes in the same manner as the {@link
  281. * #loadClass(String, boolean)} method. It is invoked by the Java virtual
  282. * machine to resolve class references. Invoking this method is equivalent
  283. * to invoking {@link #loadClass(String, boolean) <tt>loadClass(name,
  284. * false)</tt>}.
  285. *
  286. * @param name
  287. * The <a href="#name">binary name</a> of the class
  288. *
  289. * @return The resulting <tt>Class</tt> object
  290. *
  291. * @throws ClassNotFoundException
  292. * If the class was not found
  293. */
  294. public Class<?> loadClass(String name) throws ClassNotFoundException {
  295. return loadClass(name, false);
  296. }
  297.  
  298. /**
  299. * Loads the class with the specified <a href="#name">binary name</a>. The
  300. * default implementation of this method searches for classes in the
  301. * following order:
  302. *
  303. * <ol>
  304. *
  305. * <li><p> Invoke {@link #findLoadedClass(String)} to check if the class
  306. * has already been loaded. </p></li>
  307. *
  308. * <li><p> Invoke the {@link #loadClass(String) <tt>loadClass</tt>} method
  309. * on the parent class loader. If the parent is <tt>null</tt> the class
  310. * loader built-in to the virtual machine is used, instead. </p></li>
  311. *
  312. * <li><p> Invoke the {@link #findClass(String)} method to find the
  313. * class. </p></li>
  314. *
  315. * </ol>
  316. *
  317. * <p> If the class was found using the above steps, and the
  318. * <tt>resolve</tt> flag is true, this method will then invoke the {@link
  319. * #resolveClass(Class)} method on the resulting <tt>Class</tt> object.
  320. *
  321. * <p> Subclasses of <tt>ClassLoader</tt> are encouraged to override {@link
  322. * #findClass(String)}, rather than this method. </p>
  323. *
  324. * <p> Unless overridden, this method synchronizes on the result of
  325. * {@link #getClassLoadingLock <tt>getClassLoadingLock</tt>} method
  326. * during the entire class loading process.
  327. *
  328. * @param name
  329. * The <a href="#name">binary name</a> of the class
  330. *
  331. * @param resolve
  332. * If <tt>true</tt> then resolve the class
  333. *
  334. * @return The resulting <tt>Class</tt> object
  335. *
  336. * @throws ClassNotFoundException
  337. * If the class could not be found
  338. */
  339. protected Class<?> loadClass(String name, boolean resolve)
  340. throws ClassNotFoundException
  341. {
  342. synchronized (getClassLoadingLock(name)) {
  343. // First, check if the class has already been loaded
  344. Class<?> c = findLoadedClass(name);
  345. if (c == null) {
  346. long t0 = System.nanoTime();
  347. try {
  348. if (parent != null) {
  349. c = parent.loadClass(name, false);
  350. } else {
  351. c = findBootstrapClassOrNull(name);
  352. }
  353. } catch (ClassNotFoundException e) {
  354. // ClassNotFoundException thrown if class not found
  355. // from the non-null parent class loader
  356. }
  357.  
  358. if (c == null) {
  359. // If still not found, then invoke findClass in order
  360. // to find the class.
  361. long t1 = System.nanoTime();
  362. c = findClass(name);
  363.  
  364. // this is the defining class loader; record the stats
  365. sun.misc.PerfCounter.getParentDelegationTime().addTime(t1 - t0);
  366. sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1);
  367. sun.misc.PerfCounter.getFindClasses().increment();
  368. }
  369. }
  370. if (resolve) {
  371. resolveClass(c);
  372. }
  373. return c;
  374. }
  375. }
  376.  
  377. /**
  378. * Returns the lock object for class loading operations.
  379. * For backward compatibility, the default implementation of this method
  380. * behaves as follows. If this ClassLoader object is registered as
  381. * parallel capable, the method returns a dedicated object associated
  382. * with the specified class name. Otherwise, the method returns this
  383. * ClassLoader object.
  384. *
  385. * @param className
  386. * The name of the to-be-loaded class
  387. *
  388. * @return the lock for class loading operations
  389. *
  390. * @throws NullPointerException
  391. * If registered as parallel capable and <tt>className</tt> is null
  392. *
  393. * @see #loadClass(String, boolean)
  394. *
  395. * @since 1.7
  396. */
  397. protected Object getClassLoadingLock(String className) {
  398. Object lock = this;
  399. if (parallelLockMap != null) {
  400. Object newLock = new Object();
  401. lock = parallelLockMap.putIfAbsent(className, newLock);
  402. if (lock == null) {
  403. lock = newLock;
  404. }
  405. }
  406. return lock;
  407. }
  408.  
  409. // This method is invoked by the virtual machine to load a class.
  410. private Class<?> loadClassInternal(String name)
  411. throws ClassNotFoundException
  412. {
  413. // For backward compatibility, explicitly lock on 'this' when
  414. // the current class loader is not parallel capable.
  415. if (parallelLockMap == null) {
  416. synchronized (this) {
  417. return loadClass(name);
  418. }
  419. } else {
  420. return loadClass(name);
  421. }
  422. }
  423.  
  424. // Invoked by the VM after loading class with this loader.
  425. private void checkPackageAccess(Class<?> cls, ProtectionDomain pd) {
  426. final SecurityManager sm = System.getSecurityManager();
  427. if (sm != null) {
  428. if (ReflectUtil.isNonPublicProxyClass(cls)) {
  429. for (Class<?> intf: cls.getInterfaces()) {
  430. checkPackageAccess(intf, pd);
  431. }
  432. return;
  433. }
  434.  
  435. final String name = cls.getName();
  436. final int i = name.lastIndexOf('.');
  437. if (i != -1) {
  438. AccessController.doPrivileged(new PrivilegedAction<Void>() {
  439. public Void run() {
  440. sm.checkPackageAccess(name.substring(0, i));
  441. return null;
  442. }
  443. }, new AccessControlContext(new ProtectionDomain[] {pd}));
  444. }
  445. }
  446. domains.add(pd);
  447. }
  448.  
  449. /**
  450. * Finds the class with the specified <a href="#name">binary name</a>.
  451. * This method should be overridden by class loader implementations that
  452. * follow the delegation model for loading classes, and will be invoked by
  453. * the {@link #loadClass <tt>loadClass</tt>} method after checking the
  454. * parent class loader for the requested class. The default implementation
  455. * throws a <tt>ClassNotFoundException</tt>.
  456. *
  457. * @param name
  458. * The <a href="#name">binary name</a> of the class
  459. *
  460. * @return The resulting <tt>Class</tt> object
  461. *
  462. * @throws ClassNotFoundException
  463. * If the class could not be found
  464. *
  465. * @since 1.2
  466. */
  467. protected Class<?> findClass(String name) throws ClassNotFoundException {
  468. throw new ClassNotFoundException(name);
  469. }
  470.  
  471. /**
  472. * Converts an array of bytes into an instance of class <tt>Class</tt>.
  473. * Before the <tt>Class</tt> can be used it must be resolved. This method
  474. * is deprecated in favor of the version that takes a <a
  475. * href="#name">binary name</a> as its first argument, and is more secure.
  476. *
  477. * @param b
  478. * The bytes that make up the class data. The bytes in positions
  479. * <tt>off</tt> through <tt>off+len-1</tt> should have the format
  480. * of a valid class file as defined by
  481. * <cite>The Java™ Virtual Machine Specification</cite>.
  482. *
  483. * @param off
  484. * The start offset in <tt>b</tt> of the class data
  485. *
  486. * @param len
  487. * The length of the class data
  488. *
  489. * @return The <tt>Class</tt> object that was created from the specified
  490. * class data
  491. *
  492. * @throws ClassFormatError
  493. * If the data did not contain a valid class
  494. *
  495. * @throws IndexOutOfBoundsException
  496. * If either <tt>off</tt> or <tt>len</tt> is negative, or if
  497. * <tt>off+len</tt> is greater than <tt>b.length</tt>.
  498. *
  499. * @throws SecurityException
  500. * If an attempt is made to add this class to a package that
  501. * contains classes that were signed by a different set of
  502. * certificates than this class, or if an attempt is made
  503. * to define a class in a package with a fully-qualified name
  504. * that starts with "{@code java.}".
  505. *
  506. * @see #loadClass(String, boolean)
  507. * @see #resolveClass(Class)
  508. *
  509. * @deprecated Replaced by {@link #defineClass(String, byte[], int, int)
  510. * defineClass(String, byte[], int, int)}
  511. */
  512. @Deprecated
  513. protected final Class<?> defineClass(byte[] b, int off, int len)
  514. throws ClassFormatError
  515. {
  516. return defineClass(null, b, off, len, null);
  517. }
  518.  
  519. /**
  520. * Converts an array of bytes into an instance of class <tt>Class</tt>.
  521. * Before the <tt>Class</tt> can be used it must be resolved.
  522. *
  523. * <p> This method assigns a default {@link java.security.ProtectionDomain
  524. * <tt>ProtectionDomain</tt>} to the newly defined class. The
  525. * <tt>ProtectionDomain</tt> is effectively granted the same set of
  526. * permissions returned when {@link
  527. * java.security.Policy#getPermissions(java.security.CodeSource)
  528. * <tt>Policy.getPolicy().getPermissions(new CodeSource(null, null))</tt>}
  529. * is invoked. The default domain is created on the first invocation of
  530. * {@link #defineClass(String, byte[], int, int) <tt>defineClass</tt>},
  531. * and re-used on subsequent invocations.
  532. *
  533. * <p> To assign a specific <tt>ProtectionDomain</tt> to the class, use
  534. * the {@link #defineClass(String, byte[], int, int,
  535. * java.security.ProtectionDomain) <tt>defineClass</tt>} method that takes a
  536. * <tt>ProtectionDomain</tt> as one of its arguments. </p>
  537. *
  538. * @param name
  539. * The expected <a href="#name">binary name</a> of the class, or
  540. * <tt>null</tt> if not known
  541. *
  542. * @param b
  543. * The bytes that make up the class data. The bytes in positions
  544. * <tt>off</tt> through <tt>off+len-1</tt> should have the format
  545. * of a valid class file as defined by
  546. * <cite>The Java™ Virtual Machine Specification</cite>.
  547. *
  548. * @param off
  549. * The start offset in <tt>b</tt> of the class data
  550. *
  551. * @param len
  552. * The length of the class data
  553. *
  554. * @return The <tt>Class</tt> object that was created from the specified
  555. * class data.
  556. *
  557. * @throws ClassFormatError
  558. * If the data did not contain a valid class
  559. *
  560. * @throws IndexOutOfBoundsException
  561. * If either <tt>off</tt> or <tt>len</tt> is negative, or if
  562. * <tt>off+len</tt> is greater than <tt>b.length</tt>.
  563. *
  564. * @throws SecurityException
  565. * If an attempt is made to add this class to a package that
  566. * contains classes that were signed by a different set of
  567. * certificates than this class (which is unsigned), or if
  568. * <tt>name</tt> begins with "<tt>java.</tt>".
  569. *
  570. * @see #loadClass(String, boolean)
  571. * @see #resolveClass(Class)
  572. * @see java.security.CodeSource
  573. * @see java.security.SecureClassLoader
  574. *
  575. * @since 1.1
  576. */
  577. protected final Class<?> defineClass(String name, byte[] b, int off, int len)
  578. throws ClassFormatError
  579. {
  580. return defineClass(name, b, off, len, null);
  581. }
  582.  
  583. /* Determine protection domain, and check that:
  584. - not define java.* class,
  585. - signer of this class matches signers for the rest of the classes in
  586. package.
  587. */
  588. private ProtectionDomain preDefineClass(String name,
  589. ProtectionDomain pd)
  590. {
  591. if (!checkName(name))
  592. throw new NoClassDefFoundError("IllegalName: " + name);
  593.  
  594. if ((name != null) && name.startsWith("java.")) {
  595. throw new SecurityException
  596. ("Prohibited package name: " +
  597. name.substring(0, name.lastIndexOf('.')));
  598. }
  599. if (pd == null) {
  600. pd = defaultDomain;
  601. }
  602.  
  603. if (name != null) checkCerts(name, pd.getCodeSource());
  604.  
  605. return pd;
  606. }
  607.  
  608. private String defineClassSourceLocation(ProtectionDomain pd)
  609. {
  610. CodeSource cs = pd.getCodeSource();
  611. String source = null;
  612. if (cs != null && cs.getLocation() != null) {
  613. source = cs.getLocation().toString();
  614. }
  615. return source;
  616. }
  617.  
  618. private void postDefineClass(Class<?> c, ProtectionDomain pd)
  619. {
  620. if (pd.getCodeSource() != null) {
  621. Certificate certs[] = pd.getCodeSource().getCertificates();
  622. if (certs != null)
  623. setSigners(c, certs);
  624. }
  625. }
  626.  
  627. /**
  628. * Converts an array of bytes into an instance of class <tt>Class</tt>,
  629. * with an optional <tt>ProtectionDomain</tt>. If the domain is
  630. * <tt>null</tt>, then a default domain will be assigned to the class as
  631. * specified in the documentation for {@link #defineClass(String, byte[],
  632. * int, int)}. Before the class can be used it must be resolved.
  633. *
  634. * <p> The first class defined in a package determines the exact set of
  635. * certificates that all subsequent classes defined in that package must
  636. * contain. The set of certificates for a class is obtained from the
  637. * {@link java.security.CodeSource <tt>CodeSource</tt>} within the
  638. * <tt>ProtectionDomain</tt> of the class. Any classes added to that
  639. * package must contain the same set of certificates or a
  640. * <tt>SecurityException</tt> will be thrown. Note that if
  641. * <tt>name</tt> is <tt>null</tt>, this check is not performed.
  642. * You should always pass in the <a href="#name">binary name</a> of the
  643. * class you are defining as well as the bytes. This ensures that the
  644. * class you are defining is indeed the class you think it is.
  645. *
  646. * <p> The specified <tt>name</tt> cannot begin with "<tt>java.</tt>", since
  647. * all classes in the "<tt>java.*</tt> packages can only be defined by the
  648. * bootstrap class loader. If <tt>name</tt> is not <tt>null</tt>, it
  649. * must be equal to the <a href="#name">binary name</a> of the class
  650. * specified by the byte array "<tt>b</tt>", otherwise a {@link
  651. * NoClassDefFoundError <tt>NoClassDefFoundError</tt>} will be thrown. </p>
  652. *
  653. * @param name
  654. * The expected <a href="#name">binary name</a> of the class, or
  655. * <tt>null</tt> if not known
  656. *
  657. * @param b
  658. * The bytes that make up the class data. The bytes in positions
  659. * <tt>off</tt> through <tt>off+len-1</tt> should have the format
  660. * of a valid class file as defined by
  661. * <cite>The Java™ Virtual Machine Specification</cite>.
  662. *
  663. * @param off
  664. * The start offset in <tt>b</tt> of the class data
  665. *
  666. * @param len
  667. * The length of the class data
  668. *
  669. * @param protectionDomain
  670. * The ProtectionDomain of the class
  671. *
  672. * @return The <tt>Class</tt> object created from the data,
  673. * and optional <tt>ProtectionDomain</tt>.
  674. *
  675. * @throws ClassFormatError
  676. * If the data did not contain a valid class
  677. *
  678. * @throws NoClassDefFoundError
  679. * If <tt>name</tt> is not equal to the <a href="#name">binary
  680. * name</a> of the class specified by <tt>b</tt>
  681. *
  682. * @throws IndexOutOfBoundsException
  683. * If either <tt>off</tt> or <tt>len</tt> is negative, or if
  684. * <tt>off+len</tt> is greater than <tt>b.length</tt>.
  685. *
  686. * @throws SecurityException
  687. * If an attempt is made to add this class to a package that
  688. * contains classes that were signed by a different set of
  689. * certificates than this class, or if <tt>name</tt> begins with
  690. * "<tt>java.</tt>".
  691. */
  692. protected final Class<?> defineClass(String name, byte[] b, int off, int len,
  693. ProtectionDomain protectionDomain)
  694. throws ClassFormatError
  695. {
  696. protectionDomain = preDefineClass(name, protectionDomain);
  697. String source = defineClassSourceLocation(protectionDomain);
  698. Class<?> c = defineClass1(name, b, off, len, protectionDomain, source);
  699. postDefineClass(c, protectionDomain);
  700. return c;
  701. }
  702.  
  703. /**
  704. * Converts a {@link java.nio.ByteBuffer <tt>ByteBuffer</tt>}
  705. * into an instance of class <tt>Class</tt>,
  706. * with an optional <tt>ProtectionDomain</tt>. If the domain is
  707. * <tt>null</tt>, then a default domain will be assigned to the class as
  708. * specified in the documentation for {@link #defineClass(String, byte[],
  709. * int, int)}. Before the class can be used it must be resolved.
  710. *
  711. * <p>The rules about the first class defined in a package determining the
  712. * set of certificates for the package, and the restrictions on class names
  713. * are identical to those specified in the documentation for {@link
  714. * #defineClass(String, byte[], int, int, ProtectionDomain)}.
  715. *
  716. * <p> An invocation of this method of the form
  717. * <i>cl</i><tt>.defineClass(</tt><i>name</i><tt>,</tt>
  718. * <i>bBuffer</i><tt>,</tt> <i>pd</i><tt>)</tt> yields exactly the same
  719. * result as the statements
  720. *
  721. *<p> <tt>
  722. * ...<br>
  723. * byte[] temp = new byte[bBuffer.{@link
  724. * java.nio.ByteBuffer#remaining remaining}()];<br>
  725. * bBuffer.{@link java.nio.ByteBuffer#get(byte[])
  726. * get}(temp);<br>
  727. * return {@link #defineClass(String, byte[], int, int, ProtectionDomain)
  728. * cl.defineClass}(name, temp, 0,
  729. * temp.length, pd);<br>
  730. * </tt></p>
  731. *
  732. * @param name
  733. * The expected <a href="#name">binary name</a>. of the class, or
  734. * <tt>null</tt> if not known
  735. *
  736. * @param b
  737. * The bytes that make up the class data. The bytes from positions
  738. * <tt>b.position()</tt> through <tt>b.position() + b.limit() -1
  739. * </tt> should have the format of a valid class file as defined by
  740. * <cite>The Java™ Virtual Machine Specification</cite>.
  741. *
  742. * @param protectionDomain
  743. * The ProtectionDomain of the class, or <tt>null</tt>.
  744. *
  745. * @return The <tt>Class</tt> object created from the data,
  746. * and optional <tt>ProtectionDomain</tt>.
  747. *
  748. * @throws ClassFormatError
  749. * If the data did not contain a valid class.
  750. *
  751. * @throws NoClassDefFoundError
  752. * If <tt>name</tt> is not equal to the <a href="#name">binary
  753. * name</a> of the class specified by <tt>b</tt>
  754. *
  755. * @throws SecurityException
  756. * If an attempt is made to add this class to a package that
  757. * contains classes that were signed by a different set of
  758. * certificates than this class, or if <tt>name</tt> begins with
  759. * "<tt>java.</tt>".
  760. *
  761. * @see #defineClass(String, byte[], int, int, ProtectionDomain)
  762. *
  763. * @since 1.5
  764. */
  765. protected final Class<?> defineClass(String name, java.nio.ByteBuffer b,
  766. ProtectionDomain protectionDomain)
  767. throws ClassFormatError
  768. {
  769. int len = b.remaining();
  770.  
  771. // Use byte[] if not a direct ByteBufer:
  772. if (!b.isDirect()) {
  773. if (b.hasArray()) {
  774. return defineClass(name, b.array(),
  775. b.position() + b.arrayOffset(), len,
  776. protectionDomain);
  777. } else {
  778. // no array, or read-only array
  779. byte[] tb = new byte[len];
  780. b.get(tb); // get bytes out of byte buffer.
  781. return defineClass(name, tb, 0, len, protectionDomain);
  782. }
  783. }
  784.  
  785. protectionDomain = preDefineClass(name, protectionDomain);
  786. String source = defineClassSourceLocation(protectionDomain);
  787. Class<?> c = defineClass2(name, b, b.position(), len, protectionDomain, source);
  788. postDefineClass(c, protectionDomain);
  789. return c;
  790. }
  791.  
  792. private native Class<?> defineClass0(String name, byte[] b, int off, int len,
  793. ProtectionDomain pd);
  794.  
  795. private native Class<?> defineClass1(String name, byte[] b, int off, int len,
  796. ProtectionDomain pd, String source);
  797.  
  798. private native Class<?> defineClass2(String name, java.nio.ByteBuffer b,
  799. int off, int len, ProtectionDomain pd,
  800. String source);
  801.  
  802. // true if the name is null or has the potential to be a valid binary name
  803. private boolean checkName(String name) {
  804. if ((name == null) || (name.length() == 0))
  805. return true;
  806. if ((name.indexOf('/') != -1)
  807. || (!VM.allowArraySyntax() && (name.charAt(0) == '[')))
  808. return false;
  809. return true;
  810. }
  811.  
  812. private void checkCerts(String name, CodeSource cs) {
  813. int i = name.lastIndexOf('.');
  814. String pname = (i == -1) ? "" : name.substring(0, i);
  815.  
  816. Certificate[] certs = null;
  817. if (cs != null) {
  818. certs = cs.getCertificates();
  819. }
  820. Certificate[] pcerts = null;
  821. if (parallelLockMap == null) {
  822. synchronized (this) {
  823. pcerts = package2certs.get(pname);
  824. if (pcerts == null) {
  825. package2certs.put(pname, (certs == null? nocerts:certs));
  826. }
  827. }
  828. } else {
  829. pcerts = ((ConcurrentHashMap<String, Certificate[]>)package2certs).
  830. putIfAbsent(pname, (certs == null? nocerts:certs));
  831. }
  832. if (pcerts != null && !compareCerts(pcerts, certs)) {
  833. throw new SecurityException("class \""+ name +
  834. "\"'s signer information does not match signer information of other classes in the same package");
  835. }
  836. }
  837.  
  838. /**
  839. * check to make sure the certs for the new class (certs) are the same as
  840. * the certs for the first class inserted in the package (pcerts)
  841. */
  842. private boolean compareCerts(Certificate[] pcerts,
  843. Certificate[] certs)
  844. {
  845. // certs can be null, indicating no certs.
  846. if ((certs == null) || (certs.length == 0)) {
  847. return pcerts.length == 0;
  848. }
  849.  
  850. // the length must be the same at this point
  851. if (certs.length != pcerts.length)
  852. return false;
  853.  
  854. // go through and make sure all the certs in one array
  855. // are in the other and vice-versa.
  856. boolean match;
  857. for (int i = 0; i < certs.length; i++) {
  858. match = false;
  859. for (int j = 0; j < pcerts.length; j++) {
  860. if (certs[i].equals(pcerts[j])) {
  861. match = true;
  862. break;
  863. }
  864. }
  865. if (!match) return false;
  866. }
  867.  
  868. // now do the same for pcerts
  869. for (int i = 0; i < pcerts.length; i++) {
  870. match = false;
  871. for (int j = 0; j < certs.length; j++) {
  872. if (pcerts[i].equals(certs[j])) {
  873. match = true;
  874. break;
  875. }
  876. }
  877. if (!match) return false;
  878. }
  879.  
  880. return true;
  881. }
  882.  
  883. /**
  884. * Links the specified class. This (misleadingly named) method may be
  885. * used by a class loader to link a class. If the class <tt>c</tt> has
  886. * already been linked, then this method simply returns. Otherwise, the
  887. * class is linked as described in the "Execution" chapter of
  888. * <cite>The Java™ Language Specification</cite>.
  889. *
  890. * @param c
  891. * The class to link
  892. *
  893. * @throws NullPointerException
  894. * If <tt>c</tt> is <tt>null</tt>.
  895. *
  896. * @see #defineClass(String, byte[], int, int)
  897. */
  898. protected final void resolveClass(Class<?> c) {
  899. resolveClass0(c);
  900. }
  901.  
  902. private native void resolveClass0(Class<?> c);
  903.  
  904. /**
  905. * Finds a class with the specified <a href="#name">binary name</a>,
  906. * loading it if necessary.
  907. *
  908. * <p> This method loads the class through the system class loader (see
  909. * {@link #getSystemClassLoader()}). The <tt>Class</tt> object returned
  910. * might have more than one <tt>ClassLoader</tt> associated with it.
  911. * Subclasses of <tt>ClassLoader</tt> need not usually invoke this method,
  912. * because most class loaders need to override just {@link
  913. * #findClass(String)}. </p>
  914. *
  915. * @param name
  916. * The <a href="#name">binary name</a> of the class
  917. *
  918. * @return The <tt>Class</tt> object for the specified <tt>name</tt>
  919. *
  920. * @throws ClassNotFoundException
  921. * If the class could not be found
  922. *
  923. * @see #ClassLoader(ClassLoader)
  924. * @see #getParent()
  925. */
  926. protected final Class<?> findSystemClass(String name)
  927. throws ClassNotFoundException
  928. {
  929. ClassLoader system = getSystemClassLoader();
  930. if (system == null) {
  931. if (!checkName(name))
  932. throw new ClassNotFoundException(name);
  933. Class<?> cls = findBootstrapClass(name);
  934. if (cls == null) {
  935. throw new ClassNotFoundException(name);
  936. }
  937. return cls;
  938. }
  939. return system.loadClass(name);
  940. }
  941.  
  942. /**
  943. * Returns a class loaded by the bootstrap class loader;
  944. * or return null if not found.
  945. */
  946. private Class<?> findBootstrapClassOrNull(String name)
  947. {
  948. if (!checkName(name)) return null;
  949.  
  950. return findBootstrapClass(name);
  951. }
  952.  
  953. // return null if not found
  954. private native Class<?> findBootstrapClass(String name);
  955.  
  956. /**
  957. * Returns the class with the given <a href="#name">binary name</a> if this
  958. * loader has been recorded by the Java virtual machine as an initiating
  959. * loader of a class with that <a href="#name">binary name</a>. Otherwise
  960. * <tt>null</tt> is returned.
  961. *
  962. * @param name
  963. * The <a href="#name">binary name</a> of the class
  964. *
  965. * @return The <tt>Class</tt> object, or <tt>null</tt> if the class has
  966. * not been loaded
  967. *
  968. * @since 1.1
  969. */
  970. protected final Class<?> findLoadedClass(String name) {
  971. if (!checkName(name))
  972. return null;
  973. return findLoadedClass0(name);
  974. }
  975.  
  976. private native final Class<?> findLoadedClass0(String name);
  977.  
  978. /**
  979. * Sets the signers of a class. This should be invoked after defining a
  980. * class.
  981. *
  982. * @param c
  983. * The <tt>Class</tt> object
  984. *
  985. * @param signers
  986. * The signers for the class
  987. *
  988. * @since 1.1
  989. */
  990. protected final void setSigners(Class<?> c, Object[] signers) {
  991. c.setSigners(signers);
  992. }
  993.  
  994. // -- Resource --
  995.  
  996. /**
  997. * Finds the resource with the given name. A resource is some data
  998. * (images, audio, text, etc) that can be accessed by class code in a way
  999. * that is independent of the location of the code.
  1000. *
  1001. * <p> The name of a resource is a '<tt>/</tt>'-separated path name that
  1002. * identifies the resource.
  1003. *
  1004. * <p> This method will first search the parent class loader for the
  1005. * resource; if the parent is <tt>null</tt> the path of the class loader
  1006. * built-in to the virtual machine is searched. That failing, this method
  1007. * will invoke {@link #findResource(String)} to find the resource. </p>
  1008. *
  1009. * @apiNote When overriding this method it is recommended that an
  1010. * implementation ensures that any delegation is consistent with the {@link
  1011. * #getResources(java.lang.String) getResources(String)} method.
  1012. *
  1013. * @param name
  1014. * The resource name
  1015. *
  1016. * @return A <tt>URL</tt> object for reading the resource, or
  1017. * <tt>null</tt> if the resource could not be found or the invoker
  1018. * doesn't have adequate privileges to get the resource.
  1019. *
  1020. * @since 1.1
  1021. */
  1022. public URL getResource(String name) {
  1023. URL url;
  1024. if (parent != null) {
  1025. url = parent.getResource(name);
  1026. } else {
  1027. url = getBootstrapResource(name);
  1028. }
  1029. if (url == null) {
  1030. url = findResource(name);
  1031. }
  1032. return url;
  1033. }
  1034.  
  1035. /**
  1036. * Finds all the resources with the given name. A resource is some data
  1037. * (images, audio, text, etc) that can be accessed by class code in a way
  1038. * that is independent of the location of the code.
  1039. *
  1040. * <p>The name of a resource is a <tt>/</tt>-separated path name that
  1041. * identifies the resource.
  1042. *
  1043. * <p> The search order is described in the documentation for {@link
  1044. * #getResource(String)}. </p>
  1045. *
  1046. * @apiNote When overriding this method it is recommended that an
  1047. * implementation ensures that any delegation is consistent with the {@link
  1048. * #getResource(java.lang.String) getResource(String)} method. This should
  1049. * ensure that the first element returned by the Enumeration's
  1050. * {@code nextElement} method is the same resource that the
  1051. * {@code getResource(String)} method would return.
  1052. *
  1053. * @param name
  1054. * The resource name
  1055. *
  1056. * @return An enumeration of {@link java.net.URL <tt>URL</tt>} objects for
  1057. * the resource. If no resources could be found, the enumeration
  1058. * will be empty. Resources that the class loader doesn't have
  1059. * access to will not be in the enumeration.
  1060. *
  1061. * @throws IOException
  1062. * If I/O errors occur
  1063. *
  1064. * @see #findResources(String)
  1065. *
  1066. * @since 1.2
  1067. */
  1068. public Enumeration<URL> getResources(String name) throws IOException {
  1069. @SuppressWarnings("unchecked")
  1070. Enumeration<URL>[] tmp = (Enumeration<URL>[]) new Enumeration<?>[2];
  1071. if (parent != null) {
  1072. tmp[0] = parent.getResources(name);
  1073. } else {
  1074. tmp[0] = getBootstrapResources(name);
  1075. }
  1076. tmp[1] = findResources(name);
  1077.  
  1078. return new CompoundEnumeration<>(tmp);
  1079. }
  1080.  
  1081. /**
  1082. * Finds the resource with the given name. Class loader implementations
  1083. * should override this method to specify where to find resources.
  1084. *
  1085. * @param name
  1086. * The resource name
  1087. *
  1088. * @return A <tt>URL</tt> object for reading the resource, or
  1089. * <tt>null</tt> if the resource could not be found
  1090. *
  1091. * @since 1.2
  1092. */
  1093. protected URL findResource(String name) {
  1094. return null;
  1095. }
  1096.  
  1097. /**
  1098. * Returns an enumeration of {@link java.net.URL <tt>URL</tt>} objects
  1099. * representing all the resources with the given name. Class loader
  1100. * implementations should override this method to specify where to load
  1101. * resources from.
  1102. *
  1103. * @param name
  1104. * The resource name
  1105. *
  1106. * @return An enumeration of {@link java.net.URL <tt>URL</tt>} objects for
  1107. * the resources
  1108. *
  1109. * @throws IOException
  1110. * If I/O errors occur
  1111. *
  1112. * @since 1.2
  1113. */
  1114. protected Enumeration<URL> findResources(String name) throws IOException {
  1115. return java.util.Collections.emptyEnumeration();
  1116. }
  1117.  
  1118. /**
  1119. * Registers the caller as parallel capable.
  1120. * The registration succeeds if and only if all of the following
  1121. * conditions are met:
  1122. * <ol>
  1123. * <li> no instance of the caller has been created</li>
  1124. * <li> all of the super classes (except class Object) of the caller are
  1125. * registered as parallel capable</li>
  1126. * </ol>
  1127. * <p>Note that once a class loader is registered as parallel capable, there
  1128. * is no way to change it back.</p>
  1129. *
  1130. * @return true if the caller is successfully registered as
  1131. * parallel capable and false if otherwise.
  1132. *
  1133. * @since 1.7
  1134. */
  1135. @CallerSensitive
  1136. protected static boolean registerAsParallelCapable() {
  1137. Class<? extends ClassLoader> callerClass =
  1138. Reflection.getCallerClass().asSubclass(ClassLoader.class);
  1139. return ParallelLoaders.register(callerClass);
  1140. }
  1141.  
  1142. /**
  1143. * Find a resource of the specified name from the search path used to load
  1144. * classes. This method locates the resource through the system class
  1145. * loader (see {@link #getSystemClassLoader()}).
  1146. *
  1147. * @param name
  1148. * The resource name
  1149. *
  1150. * @return A {@link java.net.URL <tt>URL</tt>} object for reading the
  1151. * resource, or <tt>null</tt> if the resource could not be found
  1152. *
  1153. * @since 1.1
  1154. */
  1155. public static URL getSystemResource(String name) {
  1156. ClassLoader system = getSystemClassLoader();
  1157. if (system == null) {
  1158. return getBootstrapResource(name);
  1159. }
  1160. return system.getResource(name);
  1161. }
  1162.  
  1163. /**
  1164. * Finds all resources of the specified name from the search path used to
  1165. * load classes. The resources thus found are returned as an
  1166. * {@link java.util.Enumeration <tt>Enumeration</tt>} of {@link
  1167. * java.net.URL <tt>URL</tt>} objects.
  1168. *
  1169. * <p> The search order is described in the documentation for {@link
  1170. * #getSystemResource(String)}. </p>
  1171. *
  1172. * @param name
  1173. * The resource name
  1174. *
  1175. * @return An enumeration of resource {@link java.net.URL <tt>URL</tt>}
  1176. * objects
  1177. *
  1178. * @throws IOException
  1179. * If I/O errors occur
  1180.  
  1181. * @since 1.2
  1182. */
  1183. public static Enumeration<URL> getSystemResources(String name)
  1184. throws IOException
  1185. {
  1186. ClassLoader system = getSystemClassLoader();
  1187. if (system == null) {
  1188. return getBootstrapResources(name);
  1189. }
  1190. return system.getResources(name);
  1191. }
  1192.  
  1193. /**
  1194. * Find resources from the VM's built-in classloader.
  1195. */
  1196. private static URL getBootstrapResource(String name) {
  1197. URLClassPath ucp = getBootstrapClassPath();
  1198. Resource res = ucp.getResource(name);
  1199. return res != null ? res.getURL() : null;
  1200. }
  1201.  
  1202. /**
  1203. * Find resources from the VM's built-in classloader.
  1204. */
  1205. private static Enumeration<URL> getBootstrapResources(String name)
  1206. throws IOException
  1207. {
  1208. final Enumeration<Resource> e =
  1209. getBootstrapClassPath().getResources(name);
  1210. return new Enumeration<URL> () {
  1211. public URL nextElement() {
  1212. return e.nextElement().getURL();
  1213. }
  1214. public boolean hasMoreElements() {
  1215. return e.hasMoreElements();
  1216. }
  1217. };
  1218. }
  1219.  
  1220. // Returns the URLClassPath that is used for finding system resources.
  1221. static URLClassPath getBootstrapClassPath() {
  1222. return sun.misc.Launcher.getBootstrapClassPath();
  1223. }
  1224.  
  1225. /**
  1226. * Returns an input stream for reading the specified resource.
  1227. *
  1228. * <p> The search order is described in the documentation for {@link
  1229. * #getResource(String)}. </p>
  1230. *
  1231. * @param name
  1232. * The resource name
  1233. *
  1234. * @return An input stream for reading the resource, or <tt>null</tt>
  1235. * if the resource could not be found
  1236. *
  1237. * @since 1.1
  1238. */
  1239. public InputStream getResourceAsStream(String name) {
  1240. URL url = getResource(name);
  1241. try {
  1242. return url != null ? url.openStream() : null;
  1243. } catch (IOException e) {
  1244. return null;
  1245. }
  1246. }
  1247.  
  1248. /**
  1249. * Open for reading, a resource of the specified name from the search path
  1250. * used to load classes. This method locates the resource through the
  1251. * system class loader (see {@link #getSystemClassLoader()}).
  1252. *
  1253. * @param name
  1254. * The resource name
  1255. *
  1256. * @return An input stream for reading the resource, or <tt>null</tt>
  1257. * if the resource could not be found
  1258. *
  1259. * @since 1.1
  1260. */
  1261. public static InputStream getSystemResourceAsStream(String name) {
  1262. URL url = getSystemResource(name);
  1263. try {
  1264. return url != null ? url.openStream() : null;
  1265. } catch (IOException e) {
  1266. return null;
  1267. }
  1268. }
  1269.  
  1270. // -- Hierarchy --
  1271.  
  1272. /**
  1273. * Returns the parent class loader for delegation. Some implementations may
  1274. * use <tt>null</tt> to represent the bootstrap class loader. This method
  1275. * will return <tt>null</tt> in such implementations if this class loader's
  1276. * parent is the bootstrap class loader.
  1277. *
  1278. * <p> If a security manager is present, and the invoker's class loader is
  1279. * not <tt>null</tt> and is not an ancestor of this class loader, then this
  1280. * method invokes the security manager's {@link
  1281. * SecurityManager#checkPermission(java.security.Permission)
  1282. * <tt>checkPermission</tt>} method with a {@link
  1283. * RuntimePermission#RuntimePermission(String)
  1284. * <tt>RuntimePermission("getClassLoader")</tt>} permission to verify
  1285. * access to the parent class loader is permitted. If not, a
  1286. * <tt>SecurityException</tt> will be thrown. </p>
  1287. *
  1288. * @return The parent <tt>ClassLoader</tt>
  1289. *
  1290. * @throws SecurityException
  1291. * If a security manager exists and its <tt>checkPermission</tt>
  1292. * method doesn't allow access to this class loader's parent class
  1293. * loader.
  1294. *
  1295. * @since 1.2
  1296. */
  1297. @CallerSensitive
  1298. public final ClassLoader getParent() {
  1299. if (parent == null)
  1300. return null;
  1301. SecurityManager sm = System.getSecurityManager();
  1302. if (sm != null) {
  1303. // Check access to the parent class loader
  1304. // If the caller's class loader is same as this class loader,
  1305. // permission check is performed.
  1306. checkClassLoaderPermission(parent, Reflection.getCallerClass());
  1307. }
  1308. return parent;
  1309. }
  1310.  
  1311. /**
  1312. * Returns the system class loader for delegation. This is the default
  1313. * delegation parent for new <tt>ClassLoader</tt> instances, and is
  1314. * typically the class loader used to start the application.
  1315. *
  1316. * <p> This method is first invoked early in the runtime's startup
  1317. * sequence, at which point it creates the system class loader and sets it
  1318. * as the context class loader of the invoking <tt>Thread</tt>.
  1319. *
  1320. * <p> The default system class loader is an implementation-dependent
  1321. * instance of this class.
  1322. *
  1323. * <p> If the system property "<tt>java.system.class.loader</tt>" is defined
  1324. * when this method is first invoked then the value of that property is
  1325. * taken to be the name of a class that will be returned as the system
  1326. * class loader. The class is loaded using the default system class loader
  1327. * and must define a public constructor that takes a single parameter of
  1328. * type <tt>ClassLoader</tt> which is used as the delegation parent. An
  1329. * instance is then created using this constructor with the default system
  1330. * class loader as the parameter. The resulting class loader is defined
  1331. * to be the system class loader.
  1332. *
  1333. * <p> If a security manager is present, and the invoker's class loader is
  1334. * not <tt>null</tt> and the invoker's class loader is not the same as or
  1335. * an ancestor of the system class loader, then this method invokes the
  1336. * security manager's {@link
  1337. * SecurityManager#checkPermission(java.security.Permission)
  1338. * <tt>checkPermission</tt>} method with a {@link
  1339. * RuntimePermission#RuntimePermission(String)
  1340. * <tt>RuntimePermission("getClassLoader")</tt>} permission to verify
  1341. * access to the system class loader. If not, a
  1342. * <tt>SecurityException</tt> will be thrown. </p>
  1343. *
  1344. * @return The system <tt>ClassLoader</tt> for delegation, or
  1345. * <tt>null</tt> if none
  1346. *
  1347. * @throws SecurityException
  1348. * If a security manager exists and its <tt>checkPermission</tt>
  1349. * method doesn't allow access to the system class loader.
  1350. *
  1351. * @throws IllegalStateException
  1352. * If invoked recursively during the construction of the class
  1353. * loader specified by the "<tt>java.system.class.loader</tt>"
  1354. * property.
  1355. *
  1356. * @throws Error
  1357. * If the system property "<tt>java.system.class.loader</tt>"
  1358. * is defined but the named class could not be loaded, the
  1359. * provider class does not define the required constructor, or an
  1360. * exception is thrown by that constructor when it is invoked. The
  1361. * underlying cause of the error can be retrieved via the
  1362. * {@link Throwable#getCause()} method.
  1363. *
  1364. * @revised 1.4
  1365. */
  1366. @CallerSensitive
  1367. public static ClassLoader getSystemClassLoader() {
  1368. initSystemClassLoader();
  1369. if (scl == null) {
  1370. return null;
  1371. }
  1372. SecurityManager sm = System.getSecurityManager();
  1373. if (sm != null) {
  1374. checkClassLoaderPermission(scl, Reflection.getCallerClass());
  1375. }
  1376. return scl;
  1377. }
  1378.  
  1379. private static synchronized void initSystemClassLoader() {
  1380. if (!sclSet) {
  1381. if (scl != null)
  1382. throw new IllegalStateException("recursive invocation");
  1383. sun.misc.Launcher l = sun.misc.Launcher.getLauncher();
  1384. if (l != null) {
  1385. Throwable oops = null;
  1386. scl = l.getClassLoader();
  1387. try {
  1388. scl = AccessController.doPrivileged(
  1389. new SystemClassLoaderAction(scl));
  1390. } catch (PrivilegedActionException pae) {
  1391. oops = pae.getCause();
  1392. if (oops instanceof InvocationTargetException) {
  1393. oops = oops.getCause();
  1394. }
  1395. }
  1396. if (oops != null) {
  1397. if (oops instanceof Error) {
  1398. throw (Error) oops;
  1399. } else {
  1400. // wrap the exception
  1401. throw new Error(oops);
  1402. }
  1403. }
  1404. }
  1405. sclSet = true;
  1406. }
  1407. }
  1408.  
  1409. // Returns true if the specified class loader can be found in this class
  1410. // loader's delegation chain.
  1411. boolean isAncestor(ClassLoader cl) {
  1412. ClassLoader acl = this;
  1413. do {
  1414. acl = acl.parent;
  1415. if (cl == acl) {
  1416. return true;
  1417. }
  1418. } while (acl != null);
  1419. return false;
  1420. }
  1421.  
  1422. // Tests if class loader access requires "getClassLoader" permission
  1423. // check. A class loader 'from' can access class loader 'to' if
  1424. // class loader 'from' is same as class loader 'to' or an ancestor
  1425. // of 'to'. The class loader in a system domain can access
  1426. // any class loader.
  1427. private static boolean needsClassLoaderPermissionCheck(ClassLoader from,
  1428. ClassLoader to)
  1429. {
  1430. if (from == to)
  1431. return false;
  1432.  
  1433. if (from == null)
  1434. return false;
  1435.  
  1436. return !to.isAncestor(from);
  1437. }
  1438.  
  1439. // Returns the class's class loader, or null if none.
  1440. static ClassLoader getClassLoader(Class<?> caller) {
  1441. // This can be null if the VM is requesting it
  1442. if (caller == null) {
  1443. return null;
  1444. }
  1445. // Circumvent security check since this is package-private
  1446. return caller.getClassLoader0();
  1447. }
  1448.  
  1449. /*
  1450. * Checks RuntimePermission("getClassLoader") permission
  1451. * if caller's class loader is not null and caller's class loader
  1452. * is not the same as or an ancestor of the given cl argument.
  1453. */
  1454. static void checkClassLoaderPermission(ClassLoader cl, Class<?> caller) {
  1455. SecurityManager sm = System.getSecurityManager();
  1456. if (sm != null) {
  1457. // caller can be null if the VM is requesting it
  1458. ClassLoader ccl = getClassLoader(caller);
  1459. if (needsClassLoaderPermissionCheck(ccl, cl)) {
  1460. sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
  1461. }
  1462. }
  1463. }
  1464.  
  1465. // The class loader for the system
  1466. // @GuardedBy("ClassLoader.class")
  1467. private static ClassLoader scl;
  1468.  
  1469. // Set to true once the system class loader has been set
  1470. // @GuardedBy("ClassLoader.class")
  1471. private static boolean sclSet;
  1472.  
  1473. // -- Package --
  1474.  
  1475. /**
  1476. * Defines a package by name in this <tt>ClassLoader</tt>. This allows
  1477. * class loaders to define the packages for their classes. Packages must
  1478. * be created before the class is defined, and package names must be
  1479. * unique within a class loader and cannot be redefined or changed once
  1480. * created.
  1481. *
  1482. * @param name
  1483. * The package name
  1484. *
  1485. * @param specTitle
  1486. * The specification title
  1487. *
  1488. * @param specVersion
  1489. * The specification version
  1490. *
  1491. * @param specVendor
  1492. * The specification vendor
  1493. *
  1494. * @param implTitle
  1495. * The implementation title
  1496. *
  1497. * @param implVersion
  1498. * The implementation version
  1499. *
  1500. * @param implVendor
  1501. * The implementation vendor
  1502. *
  1503. * @param sealBase
  1504. * If not <tt>null</tt>, then this package is sealed with
  1505. * respect to the given code source {@link java.net.URL
  1506. * <tt>URL</tt>} object. Otherwise, the package is not sealed.
  1507. *
  1508. * @return The newly defined <tt>Package</tt> object
  1509. *
  1510. * @throws IllegalArgumentException
  1511. * If package name duplicates an existing package either in this
  1512. * class loader or one of its ancestors
  1513. *
  1514. * @since 1.2
  1515. */
  1516. protected Package definePackage(String name, String specTitle,
  1517. String specVersion, String specVendor,
  1518. String implTitle, String implVersion,
  1519. String implVendor, URL sealBase)
  1520. throws IllegalArgumentException
  1521. {
  1522. synchronized (packages) {
  1523. Package pkg = getPackage(name);
  1524. if (pkg != null) {
  1525. throw new IllegalArgumentException(name);
  1526. }
  1527. pkg = new Package(name, specTitle, specVersion, specVendor,
  1528. implTitle, implVersion, implVendor,
  1529. sealBase, this);
  1530. packages.put(name, pkg);
  1531. return pkg;
  1532. }
  1533. }
  1534.  
  1535. /**
  1536. * Returns a <tt>Package</tt> that has been defined by this class loader
  1537. * or any of its ancestors.
  1538. *
  1539. * @param name
  1540. * The package name
  1541. *
  1542. * @return The <tt>Package</tt> corresponding to the given name, or
  1543. * <tt>null</tt> if not found
  1544. *
  1545. * @since 1.2
  1546. */
  1547. protected Package getPackage(String name) {
  1548. Package pkg;
  1549. synchronized (packages) {
  1550. pkg = packages.get(name);
  1551. }
  1552. if (pkg == null) {
  1553. if (parent != null) {
  1554. pkg = parent.getPackage(name);
  1555. } else {
  1556. pkg = Package.getSystemPackage(name);
  1557. }
  1558. if (pkg != null) {
  1559. synchronized (packages) {
  1560. Package pkg2 = packages.get(name);
  1561. if (pkg2 == null) {
  1562. packages.put(name, pkg);
  1563. } else {
  1564. pkg = pkg2;
  1565. }
  1566. }
  1567. }
  1568. }
  1569. return pkg;
  1570. }
  1571.  
  1572. /**
  1573. * Returns all of the <tt>Packages</tt> defined by this class loader and
  1574. * its ancestors.
  1575. *
  1576. * @return The array of <tt>Package</tt> objects defined by this
  1577. * <tt>ClassLoader</tt>
  1578. *
  1579. * @since 1.2
  1580. */
  1581. protected Package[] getPackages() {
  1582. Map<String, Package> map;
  1583. synchronized (packages) {
  1584. map = new HashMap<>(packages);
  1585. }
  1586. Package[] pkgs;
  1587. if (parent != null) {
  1588. pkgs = parent.getPackages();
  1589. } else {
  1590. pkgs = Package.getSystemPackages();
  1591. }
  1592. if (pkgs != null) {
  1593. for (int i = 0; i < pkgs.length; i++) {
  1594. String pkgName = pkgs[i].getName();
  1595. if (map.get(pkgName) == null) {
  1596. map.put(pkgName, pkgs[i]);
  1597. }
  1598. }
  1599. }
  1600. return map.values().toArray(new Package[map.size()]);
  1601. }
  1602.  
  1603. // -- Native library access --
  1604.  
  1605. /**
  1606. * Returns the absolute path name of a native library. The VM invokes this
  1607. * method to locate the native libraries that belong to classes loaded with
  1608. * this class loader. If this method returns <tt>null</tt>, the VM
  1609. * searches the library along the path specified as the
  1610. * "<tt>java.library.path</tt>" property.
  1611. *
  1612. * @param libname
  1613. * The library name
  1614. *
  1615. * @return The absolute path of the native library
  1616. *
  1617. * @see System#loadLibrary(String)
  1618. * @see System#mapLibraryName(String)
  1619. *
  1620. * @since 1.2
  1621. */
  1622. protected String findLibrary(String libname) {
  1623. return null;
  1624. }
  1625.  
  1626. /**
  1627. * The inner class NativeLibrary denotes a loaded native library instance.
  1628. * Every classloader contains a vector of loaded native libraries in the
  1629. * private field <tt>nativeLibraries</tt>. The native libraries loaded
  1630. * into the system are entered into the <tt>systemNativeLibraries</tt>
  1631. * vector.
  1632. *
  1633. * <p> Every native library requires a particular version of JNI. This is
  1634. * denoted by the private <tt>jniVersion</tt> field. This field is set by
  1635. * the VM when it loads the library, and used by the VM to pass the correct
  1636. * version of JNI to the native methods. </p>
  1637. *
  1638. * @see ClassLoader
  1639. * @since 1.2
  1640. */
  1641. static class NativeLibrary {
  1642. // opaque handle to native library, used in native code.
  1643. long handle;
  1644. // the version of JNI environment the native library requires.
  1645. private int jniVersion;
  1646. // the class from which the library is loaded, also indicates
  1647. // the loader this native library belongs.
  1648. private final Class<?> fromClass;
  1649. // the canonicalized name of the native library.
  1650. // or static library name
  1651. String name;
  1652. // Indicates if the native library is linked into the VM
  1653. boolean isBuiltin;
  1654. // Indicates if the native library is loaded
  1655. boolean loaded;
  1656. native void load(String name, boolean isBuiltin);
  1657.  
  1658. native long find(String name);
  1659. native void unload(String name, boolean isBuiltin);
  1660. static native String findBuiltinLib(String name);
  1661.  
  1662. public NativeLibrary(Class<?> fromClass, String name, boolean isBuiltin) {
  1663. this.name = name;
  1664. this.fromClass = fromClass;
  1665. this.isBuiltin = isBuiltin;
  1666. }
  1667.  
  1668. protected void finalize() {
  1669. synchronized (loadedLibraryNames) {
  1670. if (fromClass.getClassLoader() != null && loaded) {
  1671. /* remove the native library name */
  1672. int size = loadedLibraryNames.size();
  1673. for (int i = 0; i < size; i++) {
  1674. if (name.equals(loadedLibraryNames.elementAt(i))) {
  1675. loadedLibraryNames.removeElementAt(i);
  1676. break;
  1677. }
  1678. }
  1679. /* unload the library. */
  1680. ClassLoader.nativeLibraryContext.push(this);
  1681. try {
  1682. unload(name, isBuiltin);
  1683. } finally {
  1684. ClassLoader.nativeLibraryContext.pop();
  1685. }
  1686. }
  1687. }
  1688. }
  1689. // Invoked in the VM to determine the context class in
  1690. // JNI_Load/JNI_Unload
  1691. static Class<?> getFromClass() {
  1692. return ClassLoader.nativeLibraryContext.peek().fromClass;
  1693. }
  1694. }
  1695.  
  1696. // All native library names we've loaded.
  1697. private static Vector<String> loadedLibraryNames = new Vector<>();
  1698.  
  1699. // Native libraries belonging to system classes.
  1700. private static Vector<NativeLibrary> systemNativeLibraries
  1701. = new Vector<>();
  1702.  
  1703. // Native libraries associated with the class loader.
  1704. private Vector<NativeLibrary> nativeLibraries = new Vector<>();
  1705.  
  1706. // native libraries being loaded/unloaded.
  1707. private static Stack<NativeLibrary> nativeLibraryContext = new Stack<>();
  1708.  
  1709. // The paths searched for libraries
  1710. private static String usr_paths[];
  1711. private static String sys_paths[];
  1712.  
  1713. private static String[] initializePath(String propname) {
  1714. String ldpath = System.getProperty(propname, "");
  1715. String ps = File.pathSeparator;
  1716. int ldlen = ldpath.length();
  1717. int i, j, n;
  1718. // Count the separators in the path
  1719. i = ldpath.indexOf(ps);
  1720. n = 0;
  1721. while (i >= 0) {
  1722. n++;
  1723. i = ldpath.indexOf(ps, i + 1);
  1724. }
  1725.  
  1726. // allocate the array of paths - n :'s = n + 1 path elements
  1727. String[] paths = new String[n + 1];
  1728.  
  1729. // Fill the array with paths from the ldpath
  1730. n = i = 0;
  1731. j = ldpath.indexOf(ps);
  1732. while (j >= 0) {
  1733. if (j - i > 0) {
  1734. paths[n++] = ldpath.substring(i, j);
  1735. } else if (j - i == 0) {
  1736. paths[n++] = ".";
  1737. }
  1738. i = j + 1;
  1739. j = ldpath.indexOf(ps, i);
  1740. }
  1741. paths[n] = ldpath.substring(i, ldlen);
  1742. return paths;
  1743. }
  1744.  
  1745. // Invoked in the java.lang.Runtime class to implement load and loadLibrary.
  1746. static void loadLibrary(Class<?> fromClass, String name,
  1747. boolean isAbsolute) {
  1748. ClassLoader loader =
  1749. (fromClass == null) ? null : fromClass.getClassLoader();
  1750. if (sys_paths == null) {
  1751. usr_paths = initializePath("java.library.path");
  1752. sys_paths = initializePath("sun.boot.library.path");
  1753. }
  1754. if (isAbsolute) {
  1755. if (loadLibrary0(fromClass, new File(name))) {
  1756. return;
  1757. }
  1758. throw new UnsatisfiedLinkError("Can't load library: " + name);
  1759. }
  1760. if (loader != null) {
  1761. String libfilename = loader.findLibrary(name);
  1762. if (libfilename != null) {
  1763. File libfile = new File(libfilename);
  1764. if (!libfile.isAbsolute()) {
  1765. throw new UnsatisfiedLinkError(
  1766. "ClassLoader.findLibrary failed to return an absolute path: " + libfilename);
  1767. }
  1768. if (loadLibrary0(fromClass, libfile)) {
  1769. return;
  1770. }
  1771. throw new UnsatisfiedLinkError("Can't load " + libfilename);
  1772. }
  1773. }
  1774. for (int i = 0 ; i < sys_paths.length ; i++) {
  1775. File libfile = new File(sys_paths[i], System.mapLibraryName(name));
  1776. if (loadLibrary0(fromClass, libfile)) {
  1777. return;
  1778. }
  1779. libfile = ClassLoaderHelper.mapAlternativeName(libfile);
  1780. if (libfile != null && loadLibrary0(fromClass, libfile)) {
  1781. return;
  1782. }
  1783. }
  1784. if (loader != null) {
  1785. for (int i = 0 ; i < usr_paths.length ; i++) {
  1786. File libfile = new File(usr_paths[i],
  1787. System.mapLibraryName(name));
  1788. if (loadLibrary0(fromClass, libfile)) {
  1789. return;
  1790. }
  1791. libfile = ClassLoaderHelper.mapAlternativeName(libfile);
  1792. if (libfile != null && loadLibrary0(fromClass, libfile)) {
  1793. return;
  1794. }
  1795. }
  1796. }
  1797. // Oops, it failed
  1798. throw new UnsatisfiedLinkError("no " + name + " in java.library.path");
  1799. }
  1800.  
  1801. private static boolean loadLibrary0(Class<?> fromClass, final File file) {
  1802. // Check to see if we're attempting to access a static library
  1803. String name = NativeLibrary.findBuiltinLib(file.getName());
  1804. boolean isBuiltin = (name != null);
  1805. if (!isBuiltin) {
  1806. boolean exists = AccessController.doPrivileged(
  1807. new PrivilegedAction<Object>() {
  1808. public Object run() {
  1809. return file.exists() ? Boolean.TRUE : null;
  1810. }})
  1811. != null;
  1812. if (!exists) {
  1813. return false;
  1814. }
  1815. try {
  1816. name = file.getCanonicalPath();
  1817. } catch (IOException e) {
  1818. return false;
  1819. }
  1820. }
  1821. ClassLoader loader =
  1822. (fromClass == null) ? null : fromClass.getClassLoader();
  1823. Vector<NativeLibrary> libs =
  1824. loader != null ? loader.nativeLibraries : systemNativeLibraries;
  1825. synchronized (libs) {
  1826. int size = libs.size();
  1827. for (int i = 0; i < size; i++) {
  1828. NativeLibrary lib = libs.elementAt(i);
  1829. if (name.equals(lib.name)) {
  1830. return true;
  1831. }
  1832. }
  1833.  
  1834. synchronized (loadedLibraryNames) {
  1835. if (loadedLibraryNames.contains(name)) {
  1836. throw new UnsatisfiedLinkError
  1837. ("Native Library " +
  1838. name +
  1839. " already loaded in another classloader");
  1840. }
  1841. /* If the library is being loaded (must be by the same thread,
  1842. * because Runtime.load and Runtime.loadLibrary are
  1843. * synchronous). The reason is can occur is that the JNI_OnLoad
  1844. * function can cause another loadLibrary invocation.
  1845. *
  1846. * Thus we can use a static stack to hold the list of libraries
  1847. * we are loading.
  1848. *
  1849. * If there is a pending load operation for the library, we
  1850. * immediately return success; otherwise, we raise
  1851. * UnsatisfiedLinkError.
  1852. */
  1853. int n = nativeLibraryContext.size();
  1854. for (int i = 0; i < n; i++) {
  1855. NativeLibrary lib = nativeLibraryContext.elementAt(i);
  1856. if (name.equals(lib.name)) {
  1857. if (loader == lib.fromClass.getClassLoader()) {
  1858. return true;
  1859. } else {
  1860. throw new UnsatisfiedLinkError
  1861. ("Native Library " +
  1862. name +
  1863. " is being loaded in another classloader");
  1864. }
  1865. }
  1866. }
  1867. NativeLibrary lib = new NativeLibrary(fromClass, name, isBuiltin);
  1868. nativeLibraryContext.push(lib);
  1869. try {
  1870. lib.load(name, isBuiltin);
  1871. } finally {
  1872. nativeLibraryContext.pop();
  1873. }
  1874. if (lib.loaded) {
  1875. loadedLibraryNames.addElement(name);
  1876. libs.addElement(lib);
  1877. return true;
  1878. }
  1879. return false;
  1880. }
  1881. }
  1882. }
  1883.  
  1884. // Invoked in the VM class linking code.
  1885. static long findNative(ClassLoader loader, String name) {
  1886. Vector<NativeLibrary> libs =
  1887. loader != null ? loader.nativeLibraries : systemNativeLibraries;
  1888. synchronized (libs) {
  1889. int size = libs.size();
  1890. for (int i = 0; i < size; i++) {
  1891. NativeLibrary lib = libs.elementAt(i);
  1892. long entry = lib.find(name);
  1893. if (entry != 0)
  1894. return entry;
  1895. }
  1896. }
  1897. return 0;
  1898. }
  1899.  
  1900. // -- Assertion management --
  1901.  
  1902. final Object assertionLock;
  1903.  
  1904. // The default toggle for assertion checking.
  1905. // @GuardedBy("assertionLock")
  1906. private boolean defaultAssertionStatus = false;
  1907.  
  1908. // Maps String packageName to Boolean package default assertion status Note
  1909. // that the default package is placed under a null map key. If this field
  1910. // is null then we are delegating assertion status queries to the VM, i.e.,
  1911. // none of this ClassLoader's assertion status modification methods have
  1912. // been invoked.
  1913. // @GuardedBy("assertionLock")
  1914. private Map<String, Boolean> packageAssertionStatus = null;
  1915.  
  1916. // Maps String fullyQualifiedClassName to Boolean assertionStatus If this
  1917. // field is null then we are delegating assertion status queries to the VM,
  1918. // i.e., none of this ClassLoader's assertion status modification methods
  1919. // have been invoked.
  1920. // @GuardedBy("assertionLock")
  1921. Map<String, Boolean> classAssertionStatus = null;
  1922.  
  1923. /**
  1924. * Sets the default assertion status for this class loader. This setting
  1925. * determines whether classes loaded by this class loader and initialized
  1926. * in the future will have assertions enabled or disabled by default.
  1927. * This setting may be overridden on a per-package or per-class basis by
  1928. * invoking {@link #setPackageAssertionStatus(String, boolean)} or {@link
  1929. * #setClassAssertionStatus(String, boolean)}.
  1930. *
  1931. * @param enabled
  1932. * <tt>true</tt> if classes loaded by this class loader will
  1933. * henceforth have assertions enabled by default, <tt>false</tt>
  1934. * if they will have assertions disabled by default.
  1935. *
  1936. * @since 1.4
  1937. */
  1938. public void setDefaultAssertionStatus(boolean enabled) {
  1939. synchronized (assertionLock) {
  1940. if (classAssertionStatus == null)
  1941. initializeJavaAssertionMaps();
  1942.  
  1943. defaultAssertionStatus = enabled;
  1944. }
  1945. }
  1946.  
  1947. /**
  1948. * Sets the package default assertion status for the named package. The
  1949. * package default assertion status determines the assertion status for
  1950. * classes initialized in the future that belong to the named package or
  1951. * any of its "subpackages".
  1952. *
  1953. * <p> A subpackage of a package named p is any package whose name begins
  1954. * with "<tt>p.</tt>". For example, <tt>javax.swing.text</tt> is a
  1955. * subpackage of <tt>javax.swing</tt>, and both <tt>java.util</tt> and
  1956. * <tt>java.lang.reflect</tt> are subpackages of <tt>java</tt>.
  1957. *
  1958. * <p> In the event that multiple package defaults apply to a given class,
  1959. * the package default pertaining to the most specific package takes
  1960. * precedence over the others. For example, if <tt>javax.lang</tt> and
  1961. * <tt>javax.lang.reflect</tt> both have package defaults associated with
  1962. * them, the latter package default applies to classes in
  1963. * <tt>javax.lang.reflect</tt>.
  1964. *
  1965. * <p> Package defaults take precedence over the class loader's default
  1966. * assertion status, and may be overridden on a per-class basis by invoking
  1967. * {@link #setClassAssertionStatus(String, boolean)}. </p>
  1968. *
  1969. * @param packageName
  1970. * The name of the package whose package default assertion status
  1971. * is to be set. A <tt>null</tt> value indicates the unnamed
  1972. * package that is "current"
  1973. * (see section 7.4.2 of
  1974. * <cite>The Java™ Language Specification</cite>.)
  1975. *
  1976. * @param enabled
  1977. * <tt>true</tt> if classes loaded by this classloader and
  1978. * belonging to the named package or any of its subpackages will
  1979. * have assertions enabled by default, <tt>false</tt> if they will
  1980. * have assertions disabled by default.
  1981. *
  1982. * @since 1.4
  1983. */
  1984. public void setPackageAssertionStatus(String packageName,
  1985. boolean enabled) {
  1986. synchronized (assertionLock) {
  1987. if (packageAssertionStatus == null)
  1988. initializeJavaAssertionMaps();
  1989.  
  1990. packageAssertionStatus.put(packageName, enabled);
  1991. }
  1992. }
  1993.  
  1994. /**
  1995. * Sets the desired assertion status for the named top-level class in this
  1996. * class loader and any nested classes contained therein. This setting
  1997. * takes precedence over the class loader's default assertion status, and
  1998. * over any applicable per-package default. This method has no effect if
  1999. * the named class has already been initialized. (Once a class is
  2000. * initialized, its assertion status cannot change.)
  2001. *
  2002. * <p> If the named class is not a top-level class, this invocation will
  2003. * have no effect on the actual assertion status of any class. </p>
  2004. *
  2005. * @param className
  2006. * The fully qualified class name of the top-level class whose
  2007. * assertion status is to be set.
  2008. *
  2009. * @param enabled
  2010. * <tt>true</tt> if the named class is to have assertions
  2011. * enabled when (and if) it is initialized, <tt>false</tt> if the
  2012. * class is to have assertions disabled.
  2013. *
  2014. * @since 1.4
  2015. */
  2016. public void setClassAssertionStatus(String className, boolean enabled) {
  2017. synchronized (assertionLock) {
  2018. if (classAssertionStatus == null)
  2019. initializeJavaAssertionMaps();
  2020.  
  2021. classAssertionStatus.put(className, enabled);
  2022. }
  2023. }
  2024.  
  2025. /**
  2026. * Sets the default assertion status for this class loader to
  2027. * <tt>false</tt> and discards any package defaults or class assertion
  2028. * status settings associated with the class loader. This method is
  2029. * provided so that class loaders can be made to ignore any command line or
  2030. * persistent assertion status settings and "start with a clean slate."
  2031. *
  2032. * @since 1.4
  2033. */
  2034. public void clearAssertionStatus() {
  2035. /*
  2036. * Whether or not "Java assertion maps" are initialized, set
  2037. * them to empty maps, effectively ignoring any present settings.
  2038. */
  2039. synchronized (assertionLock) {
  2040. classAssertionStatus = new HashMap<>();
  2041. packageAssertionStatus = new HashMap<>();
  2042. defaultAssertionStatus = false;
  2043. }
  2044. }
  2045.  
  2046. /**
  2047. * Returns the assertion status that would be assigned to the specified
  2048. * class if it were to be initialized at the time this method is invoked.
  2049. * If the named class has had its assertion status set, the most recent
  2050. * setting will be returned; otherwise, if any package default assertion
  2051. * status pertains to this class, the most recent setting for the most
  2052. * specific pertinent package default assertion status is returned;
  2053. * otherwise, this class loader's default assertion status is returned.
  2054. * </p>
  2055. *
  2056. * @param className
  2057. * The fully qualified class name of the class whose desired
  2058. * assertion status is being queried.
  2059. *
  2060. * @return The desired assertion status of the specified class.
  2061. *
  2062. * @see #setClassAssertionStatus(String, boolean)
  2063. * @see #setPackageAssertionStatus(String, boolean)
  2064. * @see #setDefaultAssertionStatus(boolean)
  2065. *
  2066. * @since 1.4
  2067. */
  2068. boolean desiredAssertionStatus(String className) {
  2069. synchronized (assertionLock) {
  2070. // assert classAssertionStatus != null;
  2071. // assert packageAssertionStatus != null;
  2072.  
  2073. // Check for a class entry
  2074. Boolean result = classAssertionStatus.get(className);
  2075. if (result != null)
  2076. return result.booleanValue();
  2077.  
  2078. // Check for most specific package entry
  2079. int dotIndex = className.lastIndexOf(".");
  2080. if (dotIndex < 0) { // default package
  2081. result = packageAssertionStatus.get(null);
  2082. if (result != null)
  2083. return result.booleanValue();
  2084. }
  2085. while(dotIndex > 0) {
  2086. className = className.substring(0, dotIndex);
  2087. result = packageAssertionStatus.get(className);
  2088. if (result != null)
  2089. return result.booleanValue();
  2090. dotIndex = className.lastIndexOf(".", dotIndex-1);
  2091. }
  2092.  
  2093. // Return the classloader default
  2094. return defaultAssertionStatus;
  2095. }
  2096. }
  2097.  
  2098. // Set up the assertions with information provided by the VM.
  2099. // Note: Should only be called inside a synchronized block
  2100. private void initializeJavaAssertionMaps() {
  2101. // assert Thread.holdsLock(assertionLock);
  2102.  
  2103. classAssertionStatus = new HashMap<>();
  2104. packageAssertionStatus = new HashMap<>();
  2105. AssertionStatusDirectives directives = retrieveDirectives();
  2106.  
  2107. for(int i = 0; i < directives.classes.length; i++)
  2108. classAssertionStatus.put(directives.classes[i],
  2109. directives.classEnabled[i]);
  2110.  
  2111. for(int i = 0; i < directives.packages.length; i++)
  2112. packageAssertionStatus.put(directives.packages[i],
  2113. directives.packageEnabled[i]);
  2114.  
  2115. defaultAssertionStatus = directives.deflt;
  2116. }
  2117.  
  2118. // Retrieves the assertion directives from the VM.
  2119. private static native AssertionStatusDirectives retrieveDirectives();
  2120. }
  2121.  
  2122. class SystemClassLoaderAction
  2123. implements PrivilegedExceptionAction<ClassLoader> {
  2124. private ClassLoader parent;
  2125.  
  2126. SystemClassLoaderAction(ClassLoader parent) {
  2127. this.parent = parent;
  2128. }
  2129.  
  2130. public ClassLoader run() throws Exception {
  2131. String cls = System.getProperty("java.system.class.loader");
  2132. if (cls == null) {
  2133. return parent;
  2134. }
  2135.  
  2136. Constructor<?> ctor = Class.forName(cls, true, parent)
  2137. .getDeclaredConstructor(new Class<?>[] { ClassLoader.class });
  2138. ClassLoader sys = (ClassLoader) ctor.newInstance(
  2139. new Object[] { parent });
  2140. Thread.currentThread().setContextClassLoader(sys);
  2141. return sys;
  2142. }
  2143. }

  

ClassLoader源码的更多相关文章

  1. 别翻了,这篇文章绝对让你深刻理解java类的加载以及ClassLoader源码分析【JVM篇二】

    目录 1.什么是类的加载(类初始化) 2.类的生命周期 3.接口的加载过程 4.解开开篇的面试题 5.理解首次主动使用 6.类加载器 7.关于命名空间 8.JVM类加载机制 9.双亲委派模型 10.C ...

  2. JVM 类加载器ClassLoader源码学习笔记

    类加载 在Java代码中,类型的加载.连接与初始化过程都是在程序运行期间完成的. 类型可以是Class,Interface, 枚举等. Java虚拟机与程序的生命周期 在如下几种情况下,Java虚拟机 ...

  3. ClassLoader源码分析与实例剖析

    在之前已经对类加载器做了不少实验了,这次主要是来分析一下ClassLoader的源码,当然主要是先从理解官方给它的注释开始,为之后自定义类加载器打好坚石的基础,下面开始: 而从类的层次结构来看也能感受 ...

  4. 【Java虚拟机7】ClassLoader源码文档翻译

    前言 学习JVM类加载器,ClassLoader这个类加载器的核心类是必须要重视的. Notes:下方蓝色文字是自己的翻译(如果有问题请指正).黑色文字是源文档.红色文字是自己的备注. ClassLo ...

  5. 第五章 类加载器ClassLoader源码解析

    说明:了解ClassLoader前,先了解 第四章 类加载机制 1.ClassLoader作用 类加载流程的"加载"阶段是由类加载器完成的. 2.类加载器结构 结构:Bootstr ...

  6. 类加载器ClassLoader源码解析

    1.ClassLoader作用 类加载流程的"加载"阶段是由类加载器完成的. 2.类加载器结构 结构:BootstrapClassLoader(祖父)-->ExtClassL ...

  7. 探索JVM底层奥秘ClassLoader源码分析

    1.JVM基本结构: *.java--------javac编译------>*.class-----ClassLoad加载---->运行时数据区------->执行引擎,接口库-- ...

  8. Tomcat源码解读:ClassLoader的设计

    Tomcat是一个经典的web server,学习tomcat的源码对于我们是有很大的帮助的.前一段时间了解了tomcat的工作的大致流程,对我的新工作有了很大的帮助.刚学习了ClassLoader( ...

  9. 深度分析 Java 的 ClassLoader 机制(源码级别)

    写在前面:Java中的所有类,必须被装载到jvm中才能运行,这个装载工作是由jvm中的类装载器完成的,类装载器所做的工作实质是把类文件从硬盘读取到内存中,JVM在加载类的时候,都是通过ClassLoa ...

随机推荐

  1. delphi 插入表格HTML代码

     <table width="174"  height="76" border="1" align="center" ...

  2. 【BZOJ1486】【HNOI2009】最小圈 分数规划 dfs判负环。

    链接: #include <stdio.h> int main() { puts("转载请注明出处[辗转山河弋流歌 by 空灰冰魂]谢谢"); puts("网 ...

  3. MapReduce数据连接

    对于不同文件里的数据,有时候有相应关系,须要进行连接(join),获得一个新的文件以便进行分析.比方有两个输入文件a.txt,b.txt,当中的数据格式分别例如以下 1 a 2 b 3 c 4 d 1 ...

  4. Nginx Rewrite 实现匹配泛域名规则

    Nginx 是一个高性能的 HTTP 和 反向代理 服务器,也是一个 IMAP/POP3/SMTP 代理服务器. Nginx 是由 Igor Sysoev 为俄罗斯访问量第二的 Rambler.ru ...

  5. 通用PE u盘装Ghost Win7系统

    http://www.tongyongpe.com/win7ghost.html 导读 通用pe工具箱是现在最老牌的的U盘装系统和维护电脑的专用工具之一,一键式制作.操作简单便捷,几乎100%支持所有 ...

  6. oracle_partition sample

    (1.) 表空间及分区表的概念 表空间: 是一个或多个数据文件的集合,所有的数据对象都存放在指定的表空间中,但主要存放的是表,所以称作表空间. 分区表: 当表中的数据量不断增大,查询数据的速度就会变慢 ...

  7. MYSQL查询今天昨天本周本月等的数据

    mysql查询本季度 今天 select * from 表名 where to_days(时间字段名) = to_days(now()); 昨天 SELECT *FROM表名WHERE TO_DAYS ...

  8. Swift 玩转gif

    众所周知,iOS默认是不支持gif类型图片的显示的,但是我们项目中常常是需要显示gif为动态图片.那肿么办?第三方库?是的 ,很多第三方都支持gif , 如果一直只停留在用第三方上,技术难有提高.上版 ...

  9. App安全之网络传输安全

    移动端App安全如果按CS结构来划分的话,主要涉及客户端本身数据安全,Client到Server网络传输的安全,客户端本身安全又包括代码安全和数据存储安全.所以当我们谈论App安全问题的时候一般来说在 ...

  10. shell判断一个变量是否为空

    判断一个变量是否为空 . 1. 变量通过" "引号引起来 如下所示:,可以得到结果为 IS NULL. #!/bin/sh para1= if [ ! -n "$para ...