PageRenderTime 64ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 1ms

/src/share/classes/java/lang/Class.java

https://bitbucket.org/chegar/jigsaw_jigsaw_jdk
Java | 3218 lines | 1151 code | 245 blank | 1822 comment | 345 complexity | bed2fb72f72c3bc5cf4049c8f29eb443 MD5 | raw file
Possible License(s): GPL-2.0, BSD-3-Clause-No-Nuclear-License-2014, LGPL-3.0

Large files files are truncated, but you can click here to view the full file

  1. /*
  2. * Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved.
  3. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4. *
  5. * This code is free software; you can redistribute it and/or modify it
  6. * under the terms of the GNU General Public License version 2 only, as
  7. * published by the Free Software Foundation. Oracle designates this
  8. * particular file as subject to the "Classpath" exception as provided
  9. * by Oracle in the LICENSE file that accompanied this code.
  10. *
  11. * This code is distributed in the hope that it will be useful, but WITHOUT
  12. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13. * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
  14. * version 2 for more details (a copy is included in the LICENSE file that
  15. * accompanied this code).
  16. *
  17. * You should have received a copy of the GNU General Public License version
  18. * 2 along with this work; if not, write to the Free Software Foundation,
  19. * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20. *
  21. * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22. * or visit www.oracle.com if you need additional information or have any
  23. * questions.
  24. */
  25. package java.lang;
  26. import java.lang.annotation.Annotation;
  27. import java.lang.module.ModuleClassLoader;
  28. import java.lang.module.ModuleNotPresentException;
  29. import java.lang.reflect.Array;
  30. import java.lang.reflect.GenericArrayType;
  31. import java.lang.reflect.Member;
  32. import java.lang.reflect.Field;
  33. import java.lang.reflect.Method;
  34. import java.lang.reflect.Constructor;
  35. import java.lang.reflect.Modifier;
  36. import java.lang.reflect.Module;
  37. import java.lang.reflect.Type;
  38. import java.lang.reflect.TypeVariable;
  39. import java.lang.reflect.InvocationTargetException;
  40. import java.lang.ref.SoftReference;
  41. import java.io.InputStream;
  42. import java.io.ObjectStreamField;
  43. import java.security.AccessController;
  44. import java.security.PrivilegedAction;
  45. import java.util.ArrayList;
  46. import java.util.Arrays;
  47. import java.util.Collection;
  48. import java.util.HashSet;
  49. import java.util.List;
  50. import java.util.Set;
  51. import java.util.Map;
  52. import java.util.HashMap;
  53. import org.openjdk.jigsaw.Platform;
  54. import sun.misc.Unsafe;
  55. import sun.reflect.ConstantPool;
  56. import sun.reflect.Reflection;
  57. import sun.reflect.ReflectionFactory;
  58. import sun.reflect.generics.factory.CoreReflectionFactory;
  59. import sun.reflect.generics.factory.GenericsFactory;
  60. import sun.reflect.generics.repository.ClassRepository;
  61. import sun.reflect.generics.repository.MethodRepository;
  62. import sun.reflect.generics.repository.ConstructorRepository;
  63. import sun.reflect.generics.scope.ClassScope;
  64. import sun.security.util.SecurityConstants;
  65. import sun.reflect.annotation.*;
  66. /**
  67. * Instances of the class {@code Class} represent classes and
  68. * interfaces in a running Java application. An enum is a kind of
  69. * class and an annotation is a kind of interface. Every array also
  70. * belongs to a class that is reflected as a {@code Class} object
  71. * that is shared by all arrays with the same element type and number
  72. * of dimensions. The primitive Java types ({@code boolean},
  73. * {@code byte}, {@code char}, {@code short},
  74. * {@code int}, {@code long}, {@code float}, and
  75. * {@code double}), and the keyword {@code void} are also
  76. * represented as {@code Class} objects.
  77. *
  78. * <p> {@code Class} has no public constructor. Instead {@code Class}
  79. * objects are constructed automatically by the Java Virtual Machine as classes
  80. * are loaded and by calls to the {@code defineClass} method in the class
  81. * loader.
  82. *
  83. * <p> The following example uses a {@code Class} object to print the
  84. * class name of an object:
  85. *
  86. * <p> <blockquote><pre>
  87. * void printClassName(Object obj) {
  88. * System.out.println("The class of " + obj +
  89. * " is " + obj.getClass().getName());
  90. * }
  91. * </pre></blockquote>
  92. *
  93. * <p> It is also possible to get the {@code Class} object for a named
  94. * type (or for void) using a class literal. See Section 15.8.2 of
  95. * <cite>The Java&trade; Language Specification</cite>.
  96. * For example:
  97. *
  98. * <p> <blockquote>
  99. * {@code System.out.println("The name of class Foo is: "+Foo.class.getName());}
  100. * </blockquote>
  101. *
  102. * @param <T> the type of the class modeled by this {@code Class}
  103. * object. For example, the type of {@code String.class} is {@code
  104. * Class<String>}. Use {@code Class<?>} if the class being modeled is
  105. * unknown.
  106. *
  107. * @author unascribed
  108. * @see java.lang.ClassLoader#defineClass(byte[], int, int)
  109. * @since JDK1.0
  110. */
  111. public final class Class<T>
  112. implements java.io.Serializable,
  113. java.lang.reflect.GenericDeclaration,
  114. java.lang.reflect.Type,
  115. java.lang.reflect.AnnotatedElement
  116. {
  117. private static final int ANNOTATION= 0x00002000;
  118. private static final int ENUM = 0x00004000;
  119. private static final int SYNTHETIC = 0x00001000;
  120. private static native void registerNatives();
  121. static {
  122. registerNatives();
  123. }
  124. /*
  125. * Constructor. Only the Java Virtual Machine creates Class
  126. * objects.
  127. */
  128. private Class() {}
  129. /**
  130. * Converts the object to a string. The string representation is the
  131. * string "class" or "interface", followed by a space, and then by the
  132. * fully qualified name of the class in the format returned by
  133. * {@code getName}. If this {@code Class} object represents a
  134. * primitive type, this method returns the name of the primitive type. If
  135. * this {@code Class} object represents void this method returns
  136. * "void".
  137. *
  138. * @return a string representation of this class object.
  139. */
  140. public String toString() {
  141. return (isInterface() ? "interface " : (isPrimitive() ? "" : "class "))
  142. + getName();
  143. }
  144. /**
  145. * Returns the {@code Class} object associated with the class or
  146. * interface with the given string name. Invoking this method is
  147. * equivalent to:
  148. *
  149. * <blockquote>
  150. * {@code Class.forName(className, true, currentLoader)}
  151. * </blockquote>
  152. *
  153. * where {@code currentLoader} denotes the defining class loader of
  154. * the current class.
  155. *
  156. * <p> For example, the following code fragment returns the
  157. * runtime {@code Class} descriptor for the class named
  158. * {@code java.lang.Thread}:
  159. *
  160. * <blockquote>
  161. * {@code Class t = Class.forName("java.lang.Thread")}
  162. * </blockquote>
  163. * <p>
  164. * A call to {@code forName("X")} causes the class named
  165. * {@code X} to be initialized.
  166. *
  167. * @param className the fully qualified name of the desired class.
  168. * @return the {@code Class} object for the class with the
  169. * specified name.
  170. * @exception LinkageError if the linkage fails
  171. * @exception ExceptionInInitializerError if the initialization provoked
  172. * by this method fails
  173. * @exception ClassNotFoundException if the class cannot be located
  174. */
  175. public static Class<?> forName(String className)
  176. throws ClassNotFoundException {
  177. return forName0(className, true, ClassLoader.getCallerClassLoader());
  178. }
  179. /**
  180. * Returns the {@code Class} object associated with the class or
  181. * interface with the given string name, using the given class loader.
  182. * Given the fully qualified name for a class or interface (in the same
  183. * format returned by {@code getName}) this method attempts to
  184. * locate, load, and link the class or interface. The specified class
  185. * loader is used to load the class or interface. If the parameter
  186. * {@code loader} is null, the class is loaded through the bootstrap
  187. * class loader. The class is initialized only if the
  188. * {@code initialize} parameter is {@code true} and if it has
  189. * not been initialized earlier.
  190. *
  191. * <p> If {@code name} denotes a primitive type or void, an attempt
  192. * will be made to locate a user-defined class in the unnamed package whose
  193. * name is {@code name}. Therefore, this method cannot be used to
  194. * obtain any of the {@code Class} objects representing primitive
  195. * types or void.
  196. *
  197. * <p> If {@code name} denotes an array class, the component type of
  198. * the array class is loaded but not initialized.
  199. *
  200. * <p> For example, in an instance method the expression:
  201. *
  202. * <blockquote>
  203. * {@code Class.forName("Foo")}
  204. * </blockquote>
  205. *
  206. * is equivalent to:
  207. *
  208. * <blockquote>
  209. * {@code Class.forName("Foo", true, this.getClass().getClassLoader())}
  210. * </blockquote>
  211. *
  212. * Note that this method throws errors related to loading, linking or
  213. * initializing as specified in Sections 12.2, 12.3 and 12.4 of <em>The
  214. * Java Language Specification</em>.
  215. * Note that this method does not check whether the requested class
  216. * is accessible to its caller.
  217. *
  218. * <p> If the {@code loader} is {@code null}, and a security
  219. * manager is present, and the caller's class loader is not null, then this
  220. * method calls the security manager's {@code checkPermission} method
  221. * with a {@code RuntimePermission("getClassLoader")} permission to
  222. * ensure it's ok to access the bootstrap class loader.
  223. *
  224. * @param name fully qualified name of the desired class
  225. * @param initialize whether the class must be initialized
  226. * @param loader class loader from which the class must be loaded
  227. * @return class object representing the desired class
  228. *
  229. * @exception LinkageError if the linkage fails
  230. * @exception ExceptionInInitializerError if the initialization provoked
  231. * by this method fails
  232. * @exception ClassNotFoundException if the class cannot be located by
  233. * the specified class loader
  234. *
  235. * @see java.lang.Class#forName(String)
  236. * @see java.lang.ClassLoader
  237. * @since 1.2
  238. */
  239. public static Class<?> forName(String name, boolean initialize,
  240. ClassLoader loader)
  241. throws ClassNotFoundException
  242. {
  243. if (loader == null) {
  244. SecurityManager sm = System.getSecurityManager();
  245. if (sm != null) {
  246. ClassLoader ccl = ClassLoader.getCallerClassLoader();
  247. if (ccl != null) {
  248. sm.checkPermission(
  249. SecurityConstants.GET_CLASSLOADER_PERMISSION);
  250. }
  251. }
  252. }
  253. return forName0(name, initialize, loader);
  254. }
  255. /** Called after security checks have been made. */
  256. private static native Class<?> forName0(String name, boolean initialize,
  257. ClassLoader loader)
  258. throws ClassNotFoundException;
  259. /**
  260. * Creates a new instance of the class represented by this {@code Class}
  261. * object. The class is instantiated as if by a {@code new}
  262. * expression with an empty argument list. The class is initialized if it
  263. * has not already been initialized.
  264. *
  265. * <p>Note that this method propagates any exception thrown by the
  266. * nullary constructor, including a checked exception. Use of
  267. * this method effectively bypasses the compile-time exception
  268. * checking that would otherwise be performed by the compiler.
  269. * The {@link
  270. * java.lang.reflect.Constructor#newInstance(java.lang.Object...)
  271. * Constructor.newInstance} method avoids this problem by wrapping
  272. * any exception thrown by the constructor in a (checked) {@link
  273. * java.lang.reflect.InvocationTargetException}.
  274. *
  275. * @return a newly allocated instance of the class represented by this
  276. * object.
  277. * @exception IllegalAccessException if the class or its nullary
  278. * constructor is not accessible.
  279. * @exception InstantiationException
  280. * if this {@code Class} represents an abstract class,
  281. * an interface, an array class, a primitive type, or void;
  282. * or if the class has no nullary constructor;
  283. * or if the instantiation fails for some other reason.
  284. * @exception ExceptionInInitializerError if the initialization
  285. * provoked by this method fails.
  286. * @exception SecurityException
  287. * If a security manager, <i>s</i>, is present and any of the
  288. * following conditions is met:
  289. *
  290. * <ul>
  291. *
  292. * <li> invocation of
  293. * {@link SecurityManager#checkMemberAccess
  294. * s.checkMemberAccess(this, Member.PUBLIC)} denies
  295. * creation of new instances of this class
  296. *
  297. * <li> the caller's class loader is not the same as or an
  298. * ancestor of the class loader for the current class and
  299. * invocation of {@link SecurityManager#checkPackageAccess
  300. * s.checkPackageAccess()} denies access to the package
  301. * of this class
  302. *
  303. * </ul>
  304. *
  305. */
  306. public T newInstance()
  307. throws InstantiationException, IllegalAccessException
  308. {
  309. if (System.getSecurityManager() != null) {
  310. checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader());
  311. }
  312. return newInstance0();
  313. }
  314. private T newInstance0()
  315. throws InstantiationException, IllegalAccessException
  316. {
  317. // NOTE: the following code may not be strictly correct under
  318. // the current Java memory model.
  319. // Constructor lookup
  320. if (cachedConstructor == null) {
  321. if (this == Class.class) {
  322. throw new IllegalAccessException(
  323. "Can not call newInstance() on the Class for java.lang.Class"
  324. );
  325. }
  326. try {
  327. Class<?>[] empty = {};
  328. final Constructor<T> c = getConstructor0(empty, Member.DECLARED);
  329. // Disable accessibility checks on the constructor
  330. // since we have to do the security check here anyway
  331. // (the stack depth is wrong for the Constructor's
  332. // security check to work)
  333. java.security.AccessController.doPrivileged(
  334. new java.security.PrivilegedAction<Void>() {
  335. public Void run() {
  336. c.setAccessible(true);
  337. return null;
  338. }
  339. });
  340. cachedConstructor = c;
  341. } catch (NoSuchMethodException e) {
  342. throw (InstantiationException)
  343. new InstantiationException(getName()).initCause(e);
  344. }
  345. }
  346. Constructor<T> tmpConstructor = cachedConstructor;
  347. // Security check (same as in java.lang.reflect.Constructor)
  348. int modifiers = tmpConstructor.getModifiers();
  349. if (!Reflection.quickCheckMemberAccess(this, modifiers)) {
  350. Class<?> caller = Reflection.getCallerClass(3);
  351. if (newInstanceCallerCache != caller) {
  352. Reflection.ensureMemberAccess(caller, this, null, modifiers);
  353. newInstanceCallerCache = caller;
  354. }
  355. }
  356. // Run constructor
  357. try {
  358. return tmpConstructor.newInstance((Object[])null);
  359. } catch (InvocationTargetException e) {
  360. Unsafe.getUnsafe().throwException(e.getTargetException());
  361. // Not reached
  362. return null;
  363. }
  364. }
  365. private volatile transient Constructor<T> cachedConstructor;
  366. private volatile transient Class<?> newInstanceCallerCache;
  367. /**
  368. * Determines if the specified {@code Object} is assignment-compatible
  369. * with the object represented by this {@code Class}. This method is
  370. * the dynamic equivalent of the Java language {@code instanceof}
  371. * operator. The method returns {@code true} if the specified
  372. * {@code Object} argument is non-null and can be cast to the
  373. * reference type represented by this {@code Class} object without
  374. * raising a {@code ClassCastException.} It returns {@code false}
  375. * otherwise.
  376. *
  377. * <p> Specifically, if this {@code Class} object represents a
  378. * declared class, this method returns {@code true} if the specified
  379. * {@code Object} argument is an instance of the represented class (or
  380. * of any of its subclasses); it returns {@code false} otherwise. If
  381. * this {@code Class} object represents an array class, this method
  382. * returns {@code true} if the specified {@code Object} argument
  383. * can be converted to an object of the array class by an identity
  384. * conversion or by a widening reference conversion; it returns
  385. * {@code false} otherwise. If this {@code Class} object
  386. * represents an interface, this method returns {@code true} if the
  387. * class or any superclass of the specified {@code Object} argument
  388. * implements this interface; it returns {@code false} otherwise. If
  389. * this {@code Class} object represents a primitive type, this method
  390. * returns {@code false}.
  391. *
  392. * @param obj the object to check
  393. * @return true if {@code obj} is an instance of this class
  394. *
  395. * @since JDK1.1
  396. */
  397. public native boolean isInstance(Object obj);
  398. /**
  399. * Determines if the class or interface represented by this
  400. * {@code Class} object is either the same as, or is a superclass or
  401. * superinterface of, the class or interface represented by the specified
  402. * {@code Class} parameter. It returns {@code true} if so;
  403. * otherwise it returns {@code false}. If this {@code Class}
  404. * object represents a primitive type, this method returns
  405. * {@code true} if the specified {@code Class} parameter is
  406. * exactly this {@code Class} object; otherwise it returns
  407. * {@code false}.
  408. *
  409. * <p> Specifically, this method tests whether the type represented by the
  410. * specified {@code Class} parameter can be converted to the type
  411. * represented by this {@code Class} object via an identity conversion
  412. * or via a widening reference conversion. See <em>The Java Language
  413. * Specification</em>, sections 5.1.1 and 5.1.4 , for details.
  414. *
  415. * @param cls the {@code Class} object to be checked
  416. * @return the {@code boolean} value indicating whether objects of the
  417. * type {@code cls} can be assigned to objects of this class
  418. * @exception NullPointerException if the specified Class parameter is
  419. * null.
  420. * @since JDK1.1
  421. */
  422. public native boolean isAssignableFrom(Class<?> cls);
  423. /**
  424. * Determines if the specified {@code Class} object represents an
  425. * interface type.
  426. *
  427. * @return {@code true} if this object represents an interface;
  428. * {@code false} otherwise.
  429. */
  430. public native boolean isInterface();
  431. /**
  432. * Determines if this {@code Class} object represents an array class.
  433. *
  434. * @return {@code true} if this object represents an array class;
  435. * {@code false} otherwise.
  436. * @since JDK1.1
  437. */
  438. public native boolean isArray();
  439. /**
  440. * Determines if the specified {@code Class} object represents a
  441. * primitive type.
  442. *
  443. * <p> There are nine predefined {@code Class} objects to represent
  444. * the eight primitive types and void. These are created by the Java
  445. * Virtual Machine, and have the same names as the primitive types that
  446. * they represent, namely {@code boolean}, {@code byte},
  447. * {@code char}, {@code short}, {@code int},
  448. * {@code long}, {@code float}, and {@code double}.
  449. *
  450. * <p> These objects may only be accessed via the following public static
  451. * final variables, and are the only {@code Class} objects for which
  452. * this method returns {@code true}.
  453. *
  454. * @return true if and only if this class represents a primitive type
  455. *
  456. * @see java.lang.Boolean#TYPE
  457. * @see java.lang.Character#TYPE
  458. * @see java.lang.Byte#TYPE
  459. * @see java.lang.Short#TYPE
  460. * @see java.lang.Integer#TYPE
  461. * @see java.lang.Long#TYPE
  462. * @see java.lang.Float#TYPE
  463. * @see java.lang.Double#TYPE
  464. * @see java.lang.Void#TYPE
  465. * @since JDK1.1
  466. */
  467. public native boolean isPrimitive();
  468. /**
  469. * Returns true if this {@code Class} object represents an annotation
  470. * type. Note that if this method returns true, {@link #isInterface()}
  471. * would also return true, as all annotation types are also interfaces.
  472. *
  473. * @return {@code true} if this class object represents an annotation
  474. * type; {@code false} otherwise
  475. * @since 1.5
  476. */
  477. public boolean isAnnotation() {
  478. return (getModifiers() & ANNOTATION) != 0;
  479. }
  480. /**
  481. * Returns {@code true} if this class is a synthetic class;
  482. * returns {@code false} otherwise.
  483. * @return {@code true} if and only if this class is a synthetic class as
  484. * defined by the Java Language Specification.
  485. * @since 1.5
  486. */
  487. public boolean isSynthetic() {
  488. return (getModifiers() & SYNTHETIC) != 0;
  489. }
  490. /**
  491. * Returns the name of the entity (class, interface, array class,
  492. * primitive type, or void) represented by this {@code Class} object,
  493. * as a {@code String}.
  494. *
  495. * <p> If this class object represents a reference type that is not an
  496. * array type then the binary name of the class is returned, as specified
  497. * by
  498. * <cite>The Java&trade; Language Specification</cite>.
  499. *
  500. * <p> If this class object represents a primitive type or void, then the
  501. * name returned is a {@code String} equal to the Java language
  502. * keyword corresponding to the primitive type or void.
  503. *
  504. * <p> If this class object represents a class of arrays, then the internal
  505. * form of the name consists of the name of the element type preceded by
  506. * one or more '{@code [}' characters representing the depth of the array
  507. * nesting. The encoding of element type names is as follows:
  508. *
  509. * <blockquote><table summary="Element types and encodings">
  510. * <tr><th> Element Type <th> &nbsp;&nbsp;&nbsp; <th> Encoding
  511. * <tr><td> boolean <td> &nbsp;&nbsp;&nbsp; <td align=center> Z
  512. * <tr><td> byte <td> &nbsp;&nbsp;&nbsp; <td align=center> B
  513. * <tr><td> char <td> &nbsp;&nbsp;&nbsp; <td align=center> C
  514. * <tr><td> class or interface
  515. * <td> &nbsp;&nbsp;&nbsp; <td align=center> L<i>classname</i>;
  516. * <tr><td> double <td> &nbsp;&nbsp;&nbsp; <td align=center> D
  517. * <tr><td> float <td> &nbsp;&nbsp;&nbsp; <td align=center> F
  518. * <tr><td> int <td> &nbsp;&nbsp;&nbsp; <td align=center> I
  519. * <tr><td> long <td> &nbsp;&nbsp;&nbsp; <td align=center> J
  520. * <tr><td> short <td> &nbsp;&nbsp;&nbsp; <td align=center> S
  521. * </table></blockquote>
  522. *
  523. * <p> The class or interface name <i>classname</i> is the binary name of
  524. * the class specified above.
  525. *
  526. * <p> Examples:
  527. * <blockquote><pre>
  528. * String.class.getName()
  529. * returns "java.lang.String"
  530. * byte.class.getName()
  531. * returns "byte"
  532. * (new Object[3]).getClass().getName()
  533. * returns "[Ljava.lang.Object;"
  534. * (new int[3][4][5][6][7][8][9]).getClass().getName()
  535. * returns "[[[[[[[I"
  536. * </pre></blockquote>
  537. *
  538. * @return the name of the class or interface
  539. * represented by this object.
  540. */
  541. public String getName() {
  542. String name = this.name;
  543. if (name == null)
  544. this.name = name = getName0();
  545. return name;
  546. }
  547. // cache the name to reduce the number of calls into the VM
  548. private transient String name;
  549. private native String getName0();
  550. /**
  551. * Returns the class loader for the class. Some implementations may use
  552. * null to represent the bootstrap class loader. This method will return
  553. * null in such implementations if this class was loaded by the bootstrap
  554. * class loader.
  555. *
  556. * <p> If a security manager is present, and the caller's class loader is
  557. * not null and the caller's class loader is not the same as or an ancestor of
  558. * the class loader for the class whose class loader is requested, then
  559. * this method calls the security manager's {@code checkPermission}
  560. * method with a {@code RuntimePermission("getClassLoader")}
  561. * permission to ensure it's ok to access the class loader for the class.
  562. *
  563. * <p>If this object
  564. * represents a primitive type or void, null is returned.
  565. *
  566. * @return the class loader that loaded the class or interface
  567. * represented by this object.
  568. * @throws SecurityException
  569. * if a security manager exists and its
  570. * {@code checkPermission} method denies
  571. * access to the class loader for the class.
  572. * @see java.lang.ClassLoader
  573. * @see SecurityManager#checkPermission
  574. * @see java.lang.RuntimePermission
  575. */
  576. public ClassLoader getClassLoader() {
  577. ClassLoader cl = getClassLoader0();
  578. if (cl == null) {
  579. // ## Should return the boot loader when running in module mode
  580. // ## but this would impact many places in the JDK that checks
  581. // ## for null class loader for bootclasspath. Also need to
  582. // ## carefully deal with bootstrapping. BootLoader is not
  583. // ## created until a system class is loaded by the libs (not VM).
  584. //
  585. return null;
  586. }
  587. SecurityManager sm = System.getSecurityManager();
  588. if (sm != null) {
  589. ClassLoader ccl = ClassLoader.getCallerClassLoader();
  590. // ## Revisit: permission required in module mode
  591. if (ClassLoader.isPlatformClassLoader(ccl) && ccl != cl && !cl.isAncestor(ccl)) {
  592. sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
  593. }
  594. }
  595. return cl;
  596. }
  597. // Package-private to allow ClassLoader access
  598. native ClassLoader getClassLoader0();
  599. /**
  600. * Returns an array of {@code TypeVariable} objects that represent the
  601. * type variables declared by the generic declaration represented by this
  602. * {@code GenericDeclaration} object, in declaration order. Returns an
  603. * array of length 0 if the underlying generic declaration declares no type
  604. * variables.
  605. *
  606. * @return an array of {@code TypeVariable} objects that represent
  607. * the type variables declared by this generic declaration
  608. * @throws java.lang.reflect.GenericSignatureFormatError if the generic
  609. * signature of this generic declaration does not conform to
  610. * the format specified in
  611. * <cite>The Java&trade; Virtual Machine Specification</cite>
  612. * @since 1.5
  613. */
  614. @SuppressWarnings("unchecked")
  615. public TypeVariable<Class<T>>[] getTypeParameters() {
  616. if (getGenericSignature() != null)
  617. return (TypeVariable<Class<T>>[])getGenericInfo().getTypeParameters();
  618. else
  619. return (TypeVariable<Class<T>>[])new TypeVariable<?>[0];
  620. }
  621. /**
  622. * Returns the {@code Class} representing the superclass of the entity
  623. * (class, interface, primitive type or void) represented by this
  624. * {@code Class}. If this {@code Class} represents either the
  625. * {@code Object} class, an interface, a primitive type, or void, then
  626. * null is returned. If this object represents an array class then the
  627. * {@code Class} object representing the {@code Object} class is
  628. * returned.
  629. *
  630. * @return the superclass of the class represented by this object.
  631. */
  632. public native Class<? super T> getSuperclass();
  633. /**
  634. * Returns the {@code Type} representing the direct superclass of
  635. * the entity (class, interface, primitive type or void) represented by
  636. * this {@code Class}.
  637. *
  638. * <p>If the superclass is a parameterized type, the {@code Type}
  639. * object returned must accurately reflect the actual type
  640. * parameters used in the source code. The parameterized type
  641. * representing the superclass is created if it had not been
  642. * created before. See the declaration of {@link
  643. * java.lang.reflect.ParameterizedType ParameterizedType} for the
  644. * semantics of the creation process for parameterized types. If
  645. * this {@code Class} represents either the {@code Object}
  646. * class, an interface, a primitive type, or void, then null is
  647. * returned. If this object represents an array class then the
  648. * {@code Class} object representing the {@code Object} class is
  649. * returned.
  650. *
  651. * @throws java.lang.reflect.GenericSignatureFormatError if the generic
  652. * class signature does not conform to the format specified in
  653. * <cite>The Java&trade; Virtual Machine Specification</cite>
  654. * @throws TypeNotPresentException if the generic superclass
  655. * refers to a non-existent type declaration
  656. * @throws java.lang.reflect.MalformedParameterizedTypeException if the
  657. * generic superclass refers to a parameterized type that cannot be
  658. * instantiated for any reason
  659. * @return the superclass of the class represented by this object
  660. * @since 1.5
  661. */
  662. public Type getGenericSuperclass() {
  663. if (getGenericSignature() != null) {
  664. // Historical irregularity:
  665. // Generic signature marks interfaces with superclass = Object
  666. // but this API returns null for interfaces
  667. if (isInterface())
  668. return null;
  669. return getGenericInfo().getSuperclass();
  670. } else
  671. return getSuperclass();
  672. }
  673. /**
  674. * Gets the package for this class. The class loader of this class is used
  675. * to find the package. If the class was loaded by the bootstrap class
  676. * loader the set of packages loaded from CLASSPATH is searched to find the
  677. * package of the class. Null is returned if no package object was created
  678. * by the class loader of this class.
  679. *
  680. * <p> Packages have attributes for versions and specifications only if the
  681. * information was defined in the manifests that accompany the classes, and
  682. * if the class loader created the package instance with the attributes
  683. * from the manifest.
  684. *
  685. * @return the package of the class, or null if no package
  686. * information is available from the archive or codebase.
  687. */
  688. public Package getPackage() {
  689. return Package.getPackage(this);
  690. }
  691. /**
  692. * Determines the interfaces implemented by the class or interface
  693. * represented by this object.
  694. *
  695. * <p> If this object represents a class, the return value is an array
  696. * containing objects representing all interfaces implemented by the
  697. * class. The order of the interface objects in the array corresponds to
  698. * the order of the interface names in the {@code implements} clause
  699. * of the declaration of the class represented by this object. For
  700. * example, given the declaration:
  701. * <blockquote>
  702. * {@code class Shimmer implements FloorWax, DessertTopping { ... }}
  703. * </blockquote>
  704. * suppose the value of {@code s} is an instance of
  705. * {@code Shimmer}; the value of the expression:
  706. * <blockquote>
  707. * {@code s.getClass().getInterfaces()[0]}
  708. * </blockquote>
  709. * is the {@code Class} object that represents interface
  710. * {@code FloorWax}; and the value of:
  711. * <blockquote>
  712. * {@code s.getClass().getInterfaces()[1]}
  713. * </blockquote>
  714. * is the {@code Class} object that represents interface
  715. * {@code DessertTopping}.
  716. *
  717. * <p> If this object represents an interface, the array contains objects
  718. * representing all interfaces extended by the interface. The order of the
  719. * interface objects in the array corresponds to the order of the interface
  720. * names in the {@code extends} clause of the declaration of the
  721. * interface represented by this object.
  722. *
  723. * <p> If this object represents a class or interface that implements no
  724. * interfaces, the method returns an array of length 0.
  725. *
  726. * <p> If this object represents a primitive type or void, the method
  727. * returns an array of length 0.
  728. *
  729. * @return an array of interfaces implemented by this class.
  730. */
  731. public native Class<?>[] getInterfaces();
  732. /**
  733. * Returns the {@code Type}s representing the interfaces
  734. * directly implemented by the class or interface represented by
  735. * this object.
  736. *
  737. * <p>If a superinterface is a parameterized type, the
  738. * {@code Type} object returned for it must accurately reflect
  739. * the actual type parameters used in the source code. The
  740. * parameterized type representing each superinterface is created
  741. * if it had not been created before. See the declaration of
  742. * {@link java.lang.reflect.ParameterizedType ParameterizedType}
  743. * for the semantics of the creation process for parameterized
  744. * types.
  745. *
  746. * <p> If this object represents a class, the return value is an
  747. * array containing objects representing all interfaces
  748. * implemented by the class. The order of the interface objects in
  749. * the array corresponds to the order of the interface names in
  750. * the {@code implements} clause of the declaration of the class
  751. * represented by this object. In the case of an array class, the
  752. * interfaces {@code Cloneable} and {@code Serializable} are
  753. * returned in that order.
  754. *
  755. * <p>If this object represents an interface, the array contains
  756. * objects representing all interfaces directly extended by the
  757. * interface. The order of the interface objects in the array
  758. * corresponds to the order of the interface names in the
  759. * {@code extends} clause of the declaration of the interface
  760. * represented by this object.
  761. *
  762. * <p>If this object represents a class or interface that
  763. * implements no interfaces, the method returns an array of length
  764. * 0.
  765. *
  766. * <p>If this object represents a primitive type or void, the
  767. * method returns an array of length 0.
  768. *
  769. * @throws java.lang.reflect.GenericSignatureFormatError
  770. * if the generic class signature does not conform to the format
  771. * specified in
  772. * <cite>The Java&trade; Virtual Machine Specification</cite>
  773. * @throws TypeNotPresentException if any of the generic
  774. * superinterfaces refers to a non-existent type declaration
  775. * @throws java.lang.reflect.MalformedParameterizedTypeException
  776. * if any of the generic superinterfaces refer to a parameterized
  777. * type that cannot be instantiated for any reason
  778. * @return an array of interfaces implemented by this class
  779. * @since 1.5
  780. */
  781. public Type[] getGenericInterfaces() {
  782. if (getGenericSignature() != null)
  783. return getGenericInfo().getSuperInterfaces();
  784. else
  785. return getInterfaces();
  786. }
  787. /**
  788. * Returns the {@code Class} representing the component type of an
  789. * array. If this class does not represent an array class this method
  790. * returns null.
  791. *
  792. * @return the {@code Class} representing the component type of this
  793. * class if this class is an array
  794. * @see java.lang.reflect.Array
  795. * @since JDK1.1
  796. */
  797. public native Class<?> getComponentType();
  798. /**
  799. * Returns the Java language modifiers for this class or interface, encoded
  800. * in an integer. The modifiers consist of the Java Virtual Machine's
  801. * constants for {@code public}, {@code protected},
  802. * {@code private}, {@code final}, {@code static},
  803. * {@code abstract} and {@code interface}; they should be decoded
  804. * using the methods of class {@code Modifier}.
  805. *
  806. * <p> If the underlying class is an array class, then its
  807. * {@code public}, {@code private} and {@code protected}
  808. * modifiers are the same as those of its component type. If this
  809. * {@code Class} represents a primitive type or void, its
  810. * {@code public} modifier is always {@code true}, and its
  811. * {@code protected} and {@code private} modifiers are always
  812. * {@code false}. If this object represents an array class, a
  813. * primitive type or void, then its {@code final} modifier is always
  814. * {@code true} and its interface modifier is always
  815. * {@code false}. The values of its other modifiers are not determined
  816. * by this specification.
  817. *
  818. * <p> The modifier encodings are defined in <em>The Java Virtual Machine
  819. * Specification</em>, table 4.1.
  820. *
  821. * @return the {@code int} representing the modifiers for this class
  822. * @see java.lang.reflect.Modifier
  823. * @since JDK1.1
  824. */
  825. public native int getModifiers();
  826. /**
  827. * Gets the signers of this class.
  828. *
  829. * @return the signers of this class, or null if there are no signers. In
  830. * particular, this method returns null if this object represents
  831. * a primitive type or void.
  832. * @since JDK1.1
  833. */
  834. public native Object[] getSigners();
  835. /**
  836. * Set the signers of this class.
  837. */
  838. native void setSigners(Object[] signers);
  839. /**
  840. * If this {@code Class} object represents a local or anonymous
  841. * class within a method, returns a {@link
  842. * java.lang.reflect.Method Method} object representing the
  843. * immediately enclosing method of the underlying class. Returns
  844. * {@code null} otherwise.
  845. *
  846. * In particular, this method returns {@code null} if the underlying
  847. * class is a local or anonymous class immediately enclosed by a type
  848. * declaration, instance initializer or static initializer.
  849. *
  850. * @return the immediately enclosing method of the underlying class, if
  851. * that class is a local or anonymous class; otherwise {@code null}.
  852. * @since 1.5
  853. */
  854. public Method getEnclosingMethod() {
  855. EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
  856. if (enclosingInfo == null)
  857. return null;
  858. else {
  859. if (!enclosingInfo.isMethod())
  860. return null;
  861. MethodRepository typeInfo = MethodRepository.make(enclosingInfo.getDescriptor(),
  862. getFactory());
  863. Class<?> returnType = toClass(typeInfo.getReturnType());
  864. Type [] parameterTypes = typeInfo.getParameterTypes();
  865. Class<?>[] parameterClasses = new Class<?>[parameterTypes.length];
  866. // Convert Types to Classes; returned types *should*
  867. // be class objects since the methodDescriptor's used
  868. // don't have generics information
  869. for(int i = 0; i < parameterClasses.length; i++)
  870. parameterClasses[i] = toClass(parameterTypes[i]);
  871. /*
  872. * Loop over all declared methods; match method name,
  873. * number of and type of parameters, *and* return
  874. * type. Matching return type is also necessary
  875. * because of covariant returns, etc.
  876. */
  877. for(Method m: enclosingInfo.getEnclosingClass().getDeclaredMethods()) {
  878. if (m.getName().equals(enclosingInfo.getName()) ) {
  879. Class<?>[] candidateParamClasses = m.getParameterTypes();
  880. if (candidateParamClasses.length == parameterClasses.length) {
  881. boolean matches = true;
  882. for(int i = 0; i < candidateParamClasses.length; i++) {
  883. if (!candidateParamClasses[i].equals(parameterClasses[i])) {
  884. matches = false;
  885. break;
  886. }
  887. }
  888. if (matches) { // finally, check return type
  889. if (m.getReturnType().equals(returnType) )
  890. return m;
  891. }
  892. }
  893. }
  894. }
  895. throw new InternalError("Enclosing method not found");
  896. }
  897. }
  898. private native Object[] getEnclosingMethod0();
  899. private EnclosingMethodInfo getEnclosingMethodInfo() {
  900. Object[] enclosingInfo = getEnclosingMethod0();
  901. if (enclosingInfo == null)
  902. return null;
  903. else {
  904. return new EnclosingMethodInfo(enclosingInfo);
  905. }
  906. }
  907. private final static class EnclosingMethodInfo {
  908. private Class<?> enclosingClass;
  909. private String name;
  910. private String descriptor;
  911. private EnclosingMethodInfo(Object[] enclosingInfo) {
  912. if (enclosingInfo.length != 3)
  913. throw new InternalError("Malformed enclosing method information");
  914. try {
  915. // The array is expected to have three elements:
  916. // the immediately enclosing class
  917. enclosingClass = (Class<?>) enclosingInfo[0];
  918. assert(enclosingClass != null);
  919. // the immediately enclosing method or constructor's
  920. // name (can be null).
  921. name = (String) enclosingInfo[1];
  922. // the immediately enclosing method or constructor's
  923. // descriptor (null iff name is).
  924. descriptor = (String) enclosingInfo[2];
  925. assert((name != null && descriptor != null) || name == descriptor);
  926. } catch (ClassCastException cce) {
  927. throw new InternalError("Invalid type in enclosing method information", cce);
  928. }
  929. }
  930. boolean isPartial() {
  931. return enclosingClass == null || name == null || descriptor == null;
  932. }
  933. boolean isConstructor() { return !isPartial() && "<init>".equals(name); }
  934. boolean isMethod() { return !isPartial() && !isConstructor() && !"<clinit>".equals(name); }
  935. Class<?> getEnclosingClass() { return enclosingClass; }
  936. String getName() { return name; }
  937. String getDescriptor() { return descriptor; }
  938. }
  939. private static Class<?> toClass(Type o) {
  940. if (o instanceof GenericArrayType)
  941. return Array.newInstance(toClass(((GenericArrayType)o).getGenericComponentType()),
  942. 0)
  943. .getClass();
  944. return (Class<?>)o;
  945. }
  946. /**
  947. * If this {@code Class} object represents a local or anonymous
  948. * class within a constructor, returns a {@link
  949. * java.lang.reflect.Constructor Constructor} object representing
  950. * the immediately enclosing constructor of the underlying
  951. * class. Returns {@code null} otherwise. In particular, this
  952. * method returns {@code null} if the underlying class is a local
  953. * or anonymous class immediately enclosed by a type declaration,
  954. * instance initializer or static initializer.
  955. *
  956. * @return the immediately enclosing constructor of the underlying class, if
  957. * that class is a local or anonymous class; otherwise {@code null}.
  958. * @since 1.5
  959. */
  960. public Constructor<?> getEnclosingConstructor() {
  961. EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
  962. if (enclosingInfo == null)
  963. return null;
  964. else {
  965. if (!enclosingInfo.isConstructor())
  966. return null;
  967. ConstructorRepository typeInfo = ConstructorRepository.make(enclosingInfo.getDescriptor(),
  968. getFactory());
  969. Type [] parameterTypes = typeInfo.getParameterTypes();
  970. Class<?>[] parameterClasses = new Class<?>[parameterTypes.length];
  971. // Convert Types to Classes; returned types *should*
  972. // be class objects since the methodDescriptor's used
  973. // don't have generics information
  974. for(int i = 0; i < parameterClasses.length; i++)
  975. parameterClasses[i] = toClass(parameterTypes[i]);
  976. /*
  977. * Loop over all declared constructors; match number
  978. * of and type of parameters.
  979. */
  980. for(Constructor<?> c: enclosingInfo.getEnclosingClass().getDeclaredConstructors()) {
  981. Class<?>[] candidateParamClasses = c.getParameterTypes();
  982. if (candidateParamClasses.length == parameterClasses.length) {
  983. boolean matches = true;
  984. for(int i = 0; i < candidateParamClasses.length; i++) {
  985. if (!candidateParamClasses[i].equals(parameterClasses[i])) {
  986. matches = false;
  987. break;
  988. }
  989. }
  990. if (matches)
  991. return c;
  992. }
  993. }
  994. throw new InternalError("Enclosing constructor not found");
  995. }
  996. }
  997. /**
  998. * If the class or interface represented by this {@code Class} object
  999. * is a member of another class, returns the {@code Class} object
  1000. * representing the class in which it was declared. This method returns
  1001. * null if this class or interface is not a member of any other class. If
  1002. * this {@code Class} object represents an array class, a primitive
  1003. * type, or void,then this method returns null.
  1004. *
  1005. * @return the declaring class for this class
  1006. * @since JDK1.1
  1007. */
  1008. public native Class<?> getDeclaringClass();
  1009. /**
  1010. * Returns the immediately enclosing class of the underlying
  1011. * class. If the underlying class is a top level class this
  1012. * method returns {@code null}.
  1013. * @return the immediately enclosing class of the underlying class
  1014. * @since 1.5
  1015. */
  1016. public Class<?> getEnclosingClass() {
  1017. // There are five kinds of classes (or interfaces):
  1018. // a) Top level classes
  1019. // b) Nested classes (static member classes)
  1020. // c) Inner classes (non-static member classes)
  1021. // d) Local classes (named classes declared within a method)
  1022. // e) Anonymous classes
  1023. // JVM Spec 4.8.6: A class must have an EnclosingMethod
  1024. // attribute if and only if it is a local class or an
  1025. // anonymous class.
  1026. EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
  1027. if (enclosingInfo == null) {
  1028. // This is a top level or a nested class or an inner class (a, b, or c)
  1029. return getDeclaringClass();
  1030. } else {
  1031. Class<?> enclosingClass = enclosingInfo.getEnclosingClass();
  1032. // This is a local class or an anonymous class (d or e)
  1033. if (enclosingClass == this || enclosingClass == null)
  1034. throw new InternalError("Malformed enclosing method information");
  1035. else
  1036. return enclosingClass;
  1037. }
  1038. }
  1039. /**
  1040. * Returns the simple name of the underlying class as given in the
  1041. * source code. Returns an empty string if the underlying class is
  1042. * anonymous.
  1043. *
  1044. * <p>The simple name of an array is the simple name of the
  1045. * component type with "[]" appended. In particular the simple
  1046. * name of an array whose component type is anonymous is "[]".
  1047. *
  1048. * @return the simple name of the underlying class
  1049. * @since 1.5
  1050. */
  1051. public String getSimpleName() {
  1052. if (isArray())
  1053. return getComponentType().getSimpleName()+"[]";
  1054. String simpleName = getSimpleBinaryName();
  1055. if (simpleName == null) { // top level class
  1056. simpleName = getName();
  1057. return simpleName.substring(simpleName.lastIndexOf(".")+1); // strip the package name
  1058. }
  1059. // According to JLS3 "Binary Compatibility" (13.1) the binary
  1060. // name of non-package classes (not top level) is the binary
  1061. // name of the immediately enclosing class followed by a '$' followed by:
  1062. // (for nested and inner classes): the simple name.
  1063. // (for local classes): 1 or more digits followed by the simple name.
  1064. // (for anonymous classes): 1 or more digits.
  1065. // Since getSimpleBinaryName() will strip the binary name of
  1066. // the immediatly enclosing class, we are now looking at a
  1067. // string that matches the regular expression "\$[0-9]*"
  1068. // followed by a simple name (considering the simple of an
  1069. // anonymous class to be the empty string).
  1070. // Remove leading "\$[0-9]*" from the name
  1071. int length = simpleName.length();
  1072. if (length < 1 || simpleName.charAt(0) != '$')
  1073. throw new InternalError("Malformed class name");
  1074. int index = 1;
  1075. while (index < length && isAsciiDigit(simpleName.charAt(index)))
  1076. index++;
  1077. // Eventually, this is the empty string iff this is an anonymous class
  1078. return simpleName.substring(index);
  1079. }
  1080. /**
  1081. * Character.isDigit answers {@code true} to some non-ascii
  1082. * digits. This one does not.
  1083. */
  1084. private static boolean isAsciiDigit(char c) {
  1085. return '0' <= c && c <= '9';
  1086. }
  1087. /**
  1088. * Returns the canonical name of the underlying class as
  1089. * defined by the Java Language Specification. Returns null if
  1090. * the underlying class does not have a canonical name (i.e., if
  1091. * it is a local or anonymous class or an array whose component
  1092. * type does not have a canonical name).
  1093. * @return the canonic…

Large files files are truncated, but you can click here to view the full file