PageRenderTime 84ms CodeModel.GetById 43ms RepoModel.GetById 1ms app.codeStats 0ms

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

https://bitbucket.org/sreilly/openjdk7u-jdk
Java | 3122 lines | 1115 code | 236 blank | 1771 comment | 337 complexity | 4ef7dd84c45093c89d371bc4a934156a 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.reflect.Array;
  27. import java.lang.reflect.GenericArrayType;
  28. import java.lang.reflect.Member;
  29. import java.lang.reflect.Field;
  30. import java.lang.reflect.Method;
  31. import java.lang.reflect.Constructor;
  32. import java.lang.reflect.GenericDeclaration;
  33. import java.lang.reflect.Modifier;
  34. import java.lang.reflect.Type;
  35. import java.lang.reflect.TypeVariable;
  36. import java.lang.reflect.InvocationTargetException;
  37. import java.lang.ref.SoftReference;
  38. import java.io.InputStream;
  39. import java.io.ObjectStreamField;
  40. import java.security.AccessController;
  41. import java.security.PrivilegedAction;
  42. import java.util.ArrayList;
  43. import java.util.Arrays;
  44. import java.util.Collection;
  45. import java.util.HashSet;
  46. import java.util.Iterator;
  47. import java.util.List;
  48. import java.util.LinkedList;
  49. import java.util.LinkedHashSet;
  50. import java.util.Set;
  51. import java.util.Map;
  52. import java.util.HashMap;
  53. import sun.misc.Unsafe;
  54. import sun.reflect.ConstantPool;
  55. import sun.reflect.Reflection;
  56. import sun.reflect.ReflectionFactory;
  57. import sun.reflect.SignatureIterator;
  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 java.lang.annotation.Annotation;
  66. import sun.reflect.annotation.*;
  67. /**
  68. * Instances of the class {@code Class} represent classes and
  69. * interfaces in a running Java application. An enum is a kind of
  70. * class and an annotation is a kind of interface. Every array also
  71. * belongs to a class that is reflected as a {@code Class} object
  72. * that is shared by all arrays with the same element type and number
  73. * of dimensions. The primitive Java types ({@code boolean},
  74. * {@code byte}, {@code char}, {@code short},
  75. * {@code int}, {@code long}, {@code float}, and
  76. * {@code double}), and the keyword {@code void} are also
  77. * represented as {@code Class} objects.
  78. *
  79. * <p> {@code Class} has no public constructor. Instead {@code Class}
  80. * objects are constructed automatically by the Java Virtual Machine as classes
  81. * are loaded and by calls to the {@code defineClass} method in the class
  82. * loader.
  83. *
  84. * <p> The following example uses a {@code Class} object to print the
  85. * class name of an object:
  86. *
  87. * <p> <blockquote><pre>
  88. * void printClassName(Object obj) {
  89. * System.out.println("The class of " + obj +
  90. * " is " + obj.getClass().getName());
  91. * }
  92. * </pre></blockquote>
  93. *
  94. * <p> It is also possible to get the {@code Class} object for a named
  95. * type (or for void) using a class literal. See Section 15.8.2 of
  96. * <cite>The Java&trade; Language Specification</cite>.
  97. * For example:
  98. *
  99. * <p> <blockquote>
  100. * {@code System.out.println("The name of class Foo is: "+Foo.class.getName());}
  101. * </blockquote>
  102. *
  103. * @param <T> the type of the class modeled by this {@code Class}
  104. * object. For example, the type of {@code String.class} is {@code
  105. * Class<String>}. Use {@code Class<?>} if the class being modeled is
  106. * unknown.
  107. *
  108. * @author unascribed
  109. * @see java.lang.ClassLoader#defineClass(byte[], int, int)
  110. * @since JDK1.0
  111. */
  112. public final
  113. class Class<T> implements java.io.Serializable,
  114. java.lang.reflect.GenericDeclaration,
  115. java.lang.reflect.Type,
  116. java.lang.reflect.AnnotatedElement {
  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 new InstantiationException(getName());
  343. }
  344. }
  345. Constructor<T> tmpConstructor = cachedConstructor;
  346. // Security check (same as in java.lang.reflect.Constructor)
  347. int modifiers = tmpConstructor.getModifiers();
  348. if (!Reflection.quickCheckMemberAccess(this, modifiers)) {
  349. Class<?> caller = Reflection.getCallerClass(3);
  350. if (newInstanceCallerCache != caller) {
  351. Reflection.ensureMemberAccess(caller, this, null, modifiers);
  352. newInstanceCallerCache = caller;
  353. }
  354. }
  355. // Run constructor
  356. try {
  357. return tmpConstructor.newInstance((Object[])null);
  358. } catch (InvocationTargetException e) {
  359. Unsafe.getUnsafe().throwException(e.getTargetException());
  360. // Not reached
  361. return null;
  362. }
  363. }
  364. private volatile transient Constructor<T> cachedConstructor;
  365. private volatile transient Class<?> newInstanceCallerCache;
  366. /**
  367. * Determines if the specified {@code Object} is assignment-compatible
  368. * with the object represented by this {@code Class}. This method is
  369. * the dynamic equivalent of the Java language {@code instanceof}
  370. * operator. The method returns {@code true} if the specified
  371. * {@code Object} argument is non-null and can be cast to the
  372. * reference type represented by this {@code Class} object without
  373. * raising a {@code ClassCastException.} It returns {@code false}
  374. * otherwise.
  375. *
  376. * <p> Specifically, if this {@code Class} object represents a
  377. * declared class, this method returns {@code true} if the specified
  378. * {@code Object} argument is an instance of the represented class (or
  379. * of any of its subclasses); it returns {@code false} otherwise. If
  380. * this {@code Class} object represents an array class, this method
  381. * returns {@code true} if the specified {@code Object} argument
  382. * can be converted to an object of the array class by an identity
  383. * conversion or by a widening reference conversion; it returns
  384. * {@code false} otherwise. If this {@code Class} object
  385. * represents an interface, this method returns {@code true} if the
  386. * class or any superclass of the specified {@code Object} argument
  387. * implements this interface; it returns {@code false} otherwise. If
  388. * this {@code Class} object represents a primitive type, this method
  389. * returns {@code false}.
  390. *
  391. * @param obj the object to check
  392. * @return true if {@code obj} is an instance of this class
  393. *
  394. * @since JDK1.1
  395. */
  396. public native boolean isInstance(Object obj);
  397. /**
  398. * Determines if the class or interface represented by this
  399. * {@code Class} object is either the same as, or is a superclass or
  400. * superinterface of, the class or interface represented by the specified
  401. * {@code Class} parameter. It returns {@code true} if so;
  402. * otherwise it returns {@code false}. If this {@code Class}
  403. * object represents a primitive type, this method returns
  404. * {@code true} if the specified {@code Class} parameter is
  405. * exactly this {@code Class} object; otherwise it returns
  406. * {@code false}.
  407. *
  408. * <p> Specifically, this method tests whether the type represented by the
  409. * specified {@code Class} parameter can be converted to the type
  410. * represented by this {@code Class} object via an identity conversion
  411. * or via a widening reference conversion. See <em>The Java Language
  412. * Specification</em>, sections 5.1.1 and 5.1.4 , for details.
  413. *
  414. * @param cls the {@code Class} object to be checked
  415. * @return the {@code boolean} value indicating whether objects of the
  416. * type {@code cls} can be assigned to objects of this class
  417. * @exception NullPointerException if the specified Class parameter is
  418. * null.
  419. * @since JDK1.1
  420. */
  421. public native boolean isAssignableFrom(Class<?> cls);
  422. /**
  423. * Determines if the specified {@code Class} object represents an
  424. * interface type.
  425. *
  426. * @return {@code true} if this object represents an interface;
  427. * {@code false} otherwise.
  428. */
  429. public native boolean isInterface();
  430. /**
  431. * Determines if this {@code Class} object represents an array class.
  432. *
  433. * @return {@code true} if this object represents an array class;
  434. * {@code false} otherwise.
  435. * @since JDK1.1
  436. */
  437. public native boolean isArray();
  438. /**
  439. * Determines if the specified {@code Class} object represents a
  440. * primitive type.
  441. *
  442. * <p> There are nine predefined {@code Class} objects to represent
  443. * the eight primitive types and void. These are created by the Java
  444. * Virtual Machine, and have the same names as the primitive types that
  445. * they represent, namely {@code boolean}, {@code byte},
  446. * {@code char}, {@code short}, {@code int},
  447. * {@code long}, {@code float}, and {@code double}.
  448. *
  449. * <p> These objects may only be accessed via the following public static
  450. * final variables, and are the only {@code Class} objects for which
  451. * this method returns {@code true}.
  452. *
  453. * @return true if and only if this class represents a primitive type
  454. *
  455. * @see java.lang.Boolean#TYPE
  456. * @see java.lang.Character#TYPE
  457. * @see java.lang.Byte#TYPE
  458. * @see java.lang.Short#TYPE
  459. * @see java.lang.Integer#TYPE
  460. * @see java.lang.Long#TYPE
  461. * @see java.lang.Float#TYPE
  462. * @see java.lang.Double#TYPE
  463. * @see java.lang.Void#TYPE
  464. * @since JDK1.1
  465. */
  466. public native boolean isPrimitive();
  467. /**
  468. * Returns true if this {@code Class} object represents an annotation
  469. * type. Note that if this method returns true, {@link #isInterface()}
  470. * would also return true, as all annotation types are also interfaces.
  471. *
  472. * @return {@code true} if this class object represents an annotation
  473. * type; {@code false} otherwise
  474. * @since 1.5
  475. */
  476. public boolean isAnnotation() {
  477. return (getModifiers() & ANNOTATION) != 0;
  478. }
  479. /**
  480. * Returns {@code true} if this class is a synthetic class;
  481. * returns {@code false} otherwise.
  482. * @return {@code true} if and only if this class is a synthetic class as
  483. * defined by the Java Language Specification.
  484. * @since 1.5
  485. */
  486. public boolean isSynthetic() {
  487. return (getModifiers() & SYNTHETIC) != 0;
  488. }
  489. /**
  490. * Returns the name of the entity (class, interface, array class,
  491. * primitive type, or void) represented by this {@code Class} object,
  492. * as a {@code String}.
  493. *
  494. * <p> If this class object represents a reference type that is not an
  495. * array type then the binary name of the class is returned, as specified
  496. * by
  497. * <cite>The Java&trade; Language Specification</cite>.
  498. *
  499. * <p> If this class object represents a primitive type or void, then the
  500. * name returned is a {@code String} equal to the Java language
  501. * keyword corresponding to the primitive type or void.
  502. *
  503. * <p> If this class object represents a class of arrays, then the internal
  504. * form of the name consists of the name of the element type preceded by
  505. * one or more '{@code [}' characters representing the depth of the array
  506. * nesting. The encoding of element type names is as follows:
  507. *
  508. * <blockquote><table summary="Element types and encodings">
  509. * <tr><th> Element Type <th> &nbsp;&nbsp;&nbsp; <th> Encoding
  510. * <tr><td> boolean <td> &nbsp;&nbsp;&nbsp; <td align=center> Z
  511. * <tr><td> byte <td> &nbsp;&nbsp;&nbsp; <td align=center> B
  512. * <tr><td> char <td> &nbsp;&nbsp;&nbsp; <td align=center> C
  513. * <tr><td> class or interface
  514. * <td> &nbsp;&nbsp;&nbsp; <td align=center> L<i>classname</i>;
  515. * <tr><td> double <td> &nbsp;&nbsp;&nbsp; <td align=center> D
  516. * <tr><td> float <td> &nbsp;&nbsp;&nbsp; <td align=center> F
  517. * <tr><td> int <td> &nbsp;&nbsp;&nbsp; <td align=center> I
  518. * <tr><td> long <td> &nbsp;&nbsp;&nbsp; <td align=center> J
  519. * <tr><td> short <td> &nbsp;&nbsp;&nbsp; <td align=center> S
  520. * </table></blockquote>
  521. *
  522. * <p> The class or interface name <i>classname</i> is the binary name of
  523. * the class specified above.
  524. *
  525. * <p> Examples:
  526. * <blockquote><pre>
  527. * String.class.getName()
  528. * returns "java.lang.String"
  529. * byte.class.getName()
  530. * returns "byte"
  531. * (new Object[3]).getClass().getName()
  532. * returns "[Ljava.lang.Object;"
  533. * (new int[3][4][5][6][7][8][9]).getClass().getName()
  534. * returns "[[[[[[[I"
  535. * </pre></blockquote>
  536. *
  537. * @return the name of the class or interface
  538. * represented by this object.
  539. */
  540. public String getName() {
  541. String name = this.name;
  542. if (name == null)
  543. this.name = name = getName0();
  544. return name;
  545. }
  546. // cache the name to reduce the number of calls into the VM
  547. private transient String name;
  548. private native String getName0();
  549. /**
  550. * Returns the class loader for the class. Some implementations may use
  551. * null to represent the bootstrap class loader. This method will return
  552. * null in such implementations if this class was loaded by the bootstrap
  553. * class loader.
  554. *
  555. * <p> If a security manager is present, and the caller's class loader is
  556. * not null and the caller's class loader is not the same as or an ancestor of
  557. * the class loader for the class whose class loader is requested, then
  558. * this method calls the security manager's {@code checkPermission}
  559. * method with a {@code RuntimePermission("getClassLoader")}
  560. * permission to ensure it's ok to access the class loader for the class.
  561. *
  562. * <p>If this object
  563. * represents a primitive type or void, null is returned.
  564. *
  565. * @return the class loader that loaded the class or interface
  566. * represented by this object.
  567. * @throws SecurityException
  568. * if a security manager exists and its
  569. * {@code checkPermission} method denies
  570. * access to the class loader for the class.
  571. * @see java.lang.ClassLoader
  572. * @see SecurityManager#checkPermission
  573. * @see java.lang.RuntimePermission
  574. */
  575. public ClassLoader getClassLoader() {
  576. ClassLoader cl = getClassLoader0();
  577. if (cl == null)
  578. return null;
  579. SecurityManager sm = System.getSecurityManager();
  580. if (sm != null) {
  581. ClassLoader ccl = ClassLoader.getCallerClassLoader();
  582. if (ccl != null && ccl != cl && !cl.isAncestor(ccl)) {
  583. sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
  584. }
  585. }
  586. return cl;
  587. }
  588. // Package-private to allow ClassLoader access
  589. native ClassLoader getClassLoader0();
  590. /**
  591. * Returns an array of {@code TypeVariable} objects that represent the
  592. * type variables declared by the generic declaration represented by this
  593. * {@code GenericDeclaration} object, in declaration order. Returns an
  594. * array of length 0 if the underlying generic declaration declares no type
  595. * variables.
  596. *
  597. * @return an array of {@code TypeVariable} objects that represent
  598. * the type variables declared by this generic declaration
  599. * @throws java.lang.reflect.GenericSignatureFormatError if the generic
  600. * signature of this generic declaration does not conform to
  601. * the format specified in
  602. * <cite>The Java&trade; Virtual Machine Specification</cite>
  603. * @since 1.5
  604. */
  605. public TypeVariable<Class<T>>[] getTypeParameters() {
  606. if (getGenericSignature() != null)
  607. return (TypeVariable<Class<T>>[])getGenericInfo().getTypeParameters();
  608. else
  609. return (TypeVariable<Class<T>>[])new TypeVariable<?>[0];
  610. }
  611. /**
  612. * Returns the {@code Class} representing the superclass of the entity
  613. * (class, interface, primitive type or void) represented by this
  614. * {@code Class}. If this {@code Class} represents either the
  615. * {@code Object} class, an interface, a primitive type, or void, then
  616. * null is returned. If this object represents an array class then the
  617. * {@code Class} object representing the {@code Object} class is
  618. * returned.
  619. *
  620. * @return the superclass of the class represented by this object.
  621. */
  622. public native Class<? super T> getSuperclass();
  623. /**
  624. * Returns the {@code Type} representing the direct superclass of
  625. * the entity (class, interface, primitive type or void) represented by
  626. * this {@code Class}.
  627. *
  628. * <p>If the superclass is a parameterized type, the {@code Type}
  629. * object returned must accurately reflect the actual type
  630. * parameters used in the source code. The parameterized type
  631. * representing the superclass is created if it had not been
  632. * created before. See the declaration of {@link
  633. * java.lang.reflect.ParameterizedType ParameterizedType} for the
  634. * semantics of the creation process for parameterized types. If
  635. * this {@code Class} represents either the {@code Object}
  636. * class, an interface, a primitive type, or void, then null is
  637. * returned. If this object represents an array class then the
  638. * {@code Class} object representing the {@code Object} class is
  639. * returned.
  640. *
  641. * @throws java.lang.reflect.GenericSignatureFormatError if the generic
  642. * class signature does not conform to the format specified in
  643. * <cite>The Java&trade; Virtual Machine Specification</cite>
  644. * @throws TypeNotPresentException if the generic superclass
  645. * refers to a non-existent type declaration
  646. * @throws java.lang.reflect.MalformedParameterizedTypeException if the
  647. * generic superclass refers to a parameterized type that cannot be
  648. * instantiated for any reason
  649. * @return the superclass of the class represented by this object
  650. * @since 1.5
  651. */
  652. public Type getGenericSuperclass() {
  653. if (getGenericSignature() != null) {
  654. // Historical irregularity:
  655. // Generic signature marks interfaces with superclass = Object
  656. // but this API returns null for interfaces
  657. if (isInterface())
  658. return null;
  659. return getGenericInfo().getSuperclass();
  660. } else
  661. return getSuperclass();
  662. }
  663. /**
  664. * Gets the package for this class. The class loader of this class is used
  665. * to find the package. If the class was loaded by the bootstrap class
  666. * loader the set of packages loaded from CLASSPATH is searched to find the
  667. * package of the class. Null is returned if no package object was created
  668. * by the class loader of this class.
  669. *
  670. * <p> Packages have attributes for versions and specifications only if the
  671. * information was defined in the manifests that accompany the classes, and
  672. * if the class loader created the package instance with the attributes
  673. * from the manifest.
  674. *
  675. * @return the package of the class, or null if no package
  676. * information is available from the archive or codebase.
  677. */
  678. public Package getPackage() {
  679. return Package.getPackage(this);
  680. }
  681. /**
  682. * Determines the interfaces implemented by the class or interface
  683. * represented by this object.
  684. *
  685. * <p> If this object represents a class, the return value is an array
  686. * containing objects representing all interfaces implemented by the
  687. * class. The order of the interface objects in the array corresponds to
  688. * the order of the interface names in the {@code implements} clause
  689. * of the declaration of the class represented by this object. For
  690. * example, given the declaration:
  691. * <blockquote>
  692. * {@code class Shimmer implements FloorWax, DessertTopping { ... }}
  693. * </blockquote>
  694. * suppose the value of {@code s} is an instance of
  695. * {@code Shimmer}; the value of the expression:
  696. * <blockquote>
  697. * {@code s.getClass().getInterfaces()[0]}
  698. * </blockquote>
  699. * is the {@code Class} object that represents interface
  700. * {@code FloorWax}; and the value of:
  701. * <blockquote>
  702. * {@code s.getClass().getInterfaces()[1]}
  703. * </blockquote>
  704. * is the {@code Class} object that represents interface
  705. * {@code DessertTopping}.
  706. *
  707. * <p> If this object represents an interface, the array contains objects
  708. * representing all interfaces extended by the interface. The order of the
  709. * interface objects in the array corresponds to the order of the interface
  710. * names in the {@code extends} clause of the declaration of the
  711. * interface represented by this object.
  712. *
  713. * <p> If this object represents a class or interface that implements no
  714. * interfaces, the method returns an array of length 0.
  715. *
  716. * <p> If this object represents a primitive type or void, the method
  717. * returns an array of length 0.
  718. *
  719. * @return an array of interfaces implemented by this class.
  720. */
  721. public native Class<?>[] getInterfaces();
  722. /**
  723. * Returns the {@code Type}s representing the interfaces
  724. * directly implemented by the class or interface represented by
  725. * this object.
  726. *
  727. * <p>If a superinterface is a parameterized type, the
  728. * {@code Type} object returned for it must accurately reflect
  729. * the actual type parameters used in the source code. The
  730. * parameterized type representing each superinterface is created
  731. * if it had not been created before. See the declaration of
  732. * {@link java.lang.reflect.ParameterizedType ParameterizedType}
  733. * for the semantics of the creation process for parameterized
  734. * types.
  735. *
  736. * <p> If this object represents a class, the return value is an
  737. * array containing objects representing all interfaces
  738. * implemented by the class. The order of the interface objects in
  739. * the array corresponds to the order of the interface names in
  740. * the {@code implements} clause of the declaration of the class
  741. * represented by this object. In the case of an array class, the
  742. * interfaces {@code Cloneable} and {@code Serializable} are
  743. * returned in that order.
  744. *
  745. * <p>If this object represents an interface, the array contains
  746. * objects representing all interfaces directly extended by the
  747. * interface. The order of the interface objects in the array
  748. * corresponds to the order of the interface names in the
  749. * {@code extends} clause of the declaration of the interface
  750. * represented by this object.
  751. *
  752. * <p>If this object represents a class or interface that
  753. * implements no interfaces, the method returns an array of length
  754. * 0.
  755. *
  756. * <p>If this object represents a primitive type or void, the
  757. * method returns an array of length 0.
  758. *
  759. * @throws java.lang.reflect.GenericSignatureFormatError
  760. * if the generic class signature does not conform to the format
  761. * specified in
  762. * <cite>The Java&trade; Virtual Machine Specification</cite>
  763. * @throws TypeNotPresentException if any of the generic
  764. * superinterfaces refers to a non-existent type declaration
  765. * @throws java.lang.reflect.MalformedParameterizedTypeException
  766. * if any of the generic superinterfaces refer to a parameterized
  767. * type that cannot be instantiated for any reason
  768. * @return an array of interfaces implemented by this class
  769. * @since 1.5
  770. */
  771. public Type[] getGenericInterfaces() {
  772. if (getGenericSignature() != null)
  773. return getGenericInfo().getSuperInterfaces();
  774. else
  775. return getInterfaces();
  776. }
  777. /**
  778. * Returns the {@code Class} representing the component type of an
  779. * array. If this class does not represent an array class this method
  780. * returns null.
  781. *
  782. * @return the {@code Class} representing the component type of this
  783. * class if this class is an array
  784. * @see java.lang.reflect.Array
  785. * @since JDK1.1
  786. */
  787. public native Class<?> getComponentType();
  788. /**
  789. * Returns the Java language modifiers for this class or interface, encoded
  790. * in an integer. The modifiers consist of the Java Virtual Machine's
  791. * constants for {@code public}, {@code protected},
  792. * {@code private}, {@code final}, {@code static},
  793. * {@code abstract} and {@code interface}; they should be decoded
  794. * using the methods of class {@code Modifier}.
  795. *
  796. * <p> If the underlying class is an array class, then its
  797. * {@code public}, {@code private} and {@code protected}
  798. * modifiers are the same as those of its component type. If this
  799. * {@code Class} represents a primitive type or void, its
  800. * {@code public} modifier is always {@code true}, and its
  801. * {@code protected} and {@code private} modifiers are always
  802. * {@code false}. If this object represents an array class, a
  803. * primitive type or void, then its {@code final} modifier is always
  804. * {@code true} and its interface modifier is always
  805. * {@code false}. The values of its other modifiers are not determined
  806. * by this specification.
  807. *
  808. * <p> The modifier encodings are defined in <em>The Java Virtual Machine
  809. * Specification</em>, table 4.1.
  810. *
  811. * @return the {@code int} representing the modifiers for this class
  812. * @see java.lang.reflect.Modifier
  813. * @since JDK1.1
  814. */
  815. public native int getModifiers();
  816. /**
  817. * Gets the signers of this class.
  818. *
  819. * @return the signers of this class, or null if there are no signers. In
  820. * particular, this method returns null if this object represents
  821. * a primitive type or void.
  822. * @since JDK1.1
  823. */
  824. public native Object[] getSigners();
  825. /**
  826. * Set the signers of this class.
  827. */
  828. native void setSigners(Object[] signers);
  829. /**
  830. * If this {@code Class} object represents a local or anonymous
  831. * class within a method, returns a {@link
  832. * java.lang.reflect.Method Method} object representing the
  833. * immediately enclosing method of the underlying class. Returns
  834. * {@code null} otherwise.
  835. *
  836. * In particular, this method returns {@code null} if the underlying
  837. * class is a local or anonymous class immediately enclosed by a type
  838. * declaration, instance initializer or static initializer.
  839. *
  840. * @return the immediately enclosing method of the underlying class, if
  841. * that class is a local or anonymous class; otherwise {@code null}.
  842. * @since 1.5
  843. */
  844. public Method getEnclosingMethod() {
  845. EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
  846. if (enclosingInfo == null)
  847. return null;
  848. else {
  849. if (!enclosingInfo.isMethod())
  850. return null;
  851. MethodRepository typeInfo = MethodRepository.make(enclosingInfo.getDescriptor(),
  852. getFactory());
  853. Class<?> returnType = toClass(typeInfo.getReturnType());
  854. Type [] parameterTypes = typeInfo.getParameterTypes();
  855. Class<?>[] parameterClasses = new Class<?>[parameterTypes.length];
  856. // Convert Types to Classes; returned types *should*
  857. // be class objects since the methodDescriptor's used
  858. // don't have generics information
  859. for(int i = 0; i < parameterClasses.length; i++)
  860. parameterClasses[i] = toClass(parameterTypes[i]);
  861. /*
  862. * Loop over all declared methods; match method name,
  863. * number of and type of parameters, *and* return
  864. * type. Matching return type is also necessary
  865. * because of covariant returns, etc.
  866. */
  867. for(Method m: enclosingInfo.getEnclosingClass().getDeclaredMethods()) {
  868. if (m.getName().equals(enclosingInfo.getName()) ) {
  869. Class<?>[] candidateParamClasses = m.getParameterTypes();
  870. if (candidateParamClasses.length == parameterClasses.length) {
  871. boolean matches = true;
  872. for(int i = 0; i < candidateParamClasses.length; i++) {
  873. if (!candidateParamClasses[i].equals(parameterClasses[i])) {
  874. matches = false;
  875. break;
  876. }
  877. }
  878. if (matches) { // finally, check return type
  879. if (m.getReturnType().equals(returnType) )
  880. return m;
  881. }
  882. }
  883. }
  884. }
  885. throw new InternalError("Enclosing method not found");
  886. }
  887. }
  888. private native Object[] getEnclosingMethod0();
  889. private EnclosingMethodInfo getEnclosingMethodInfo() {
  890. Object[] enclosingInfo = getEnclosingMethod0();
  891. if (enclosingInfo == null)
  892. return null;
  893. else {
  894. return new EnclosingMethodInfo(enclosingInfo);
  895. }
  896. }
  897. private final static class EnclosingMethodInfo {
  898. private Class<?> enclosingClass;
  899. private String name;
  900. private String descriptor;
  901. private EnclosingMethodInfo(Object[] enclosingInfo) {
  902. if (enclosingInfo.length != 3)
  903. throw new InternalError("Malformed enclosing method information");
  904. try {
  905. // The array is expected to have three elements:
  906. // the immediately enclosing class
  907. enclosingClass = (Class<?>) enclosingInfo[0];
  908. assert(enclosingClass != null);
  909. // the immediately enclosing method or constructor's
  910. // name (can be null).
  911. name = (String) enclosingInfo[1];
  912. // the immediately enclosing method or constructor's
  913. // descriptor (null iff name is).
  914. descriptor = (String) enclosingInfo[2];
  915. assert((name != null && descriptor != null) || name == descriptor);
  916. } catch (ClassCastException cce) {
  917. throw new InternalError("Invalid type in enclosing method information");
  918. }
  919. }
  920. boolean isPartial() {
  921. return enclosingClass == null || name == null || descriptor == null;
  922. }
  923. boolean isConstructor() { return !isPartial() && "<init>".equals(name); }
  924. boolean isMethod() { return !isPartial() && !isConstructor() && !"<clinit>".equals(name); }
  925. Class<?> getEnclosingClass() { return enclosingClass; }
  926. String getName() { return name; }
  927. String getDescriptor() { return descriptor; }
  928. }
  929. private static Class<?> toClass(Type o) {
  930. if (o instanceof GenericArrayType)
  931. return Array.newInstance(toClass(((GenericArrayType)o).getGenericComponentType()),
  932. 0)
  933. .getClass();
  934. return (Class<?>)o;
  935. }
  936. /**
  937. * If this {@code Class} object represents a local or anonymous
  938. * class within a constructor, returns a {@link
  939. * java.lang.reflect.Constructor Constructor} object representing
  940. * the immediately enclosing constructor of the underlying
  941. * class. Returns {@code null} otherwise. In particular, this
  942. * method returns {@code null} if the underlying class is a local
  943. * or anonymous class immediately enclosed by a type declaration,
  944. * instance initializer or static initializer.
  945. *
  946. * @return the immediately enclosing constructor of the underlying class, if
  947. * that class is a local or anonymous class; otherwise {@code null}.
  948. * @since 1.5
  949. */
  950. public Constructor<?> getEnclosingConstructor() {
  951. EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
  952. if (enclosingInfo == null)
  953. return null;
  954. else {
  955. if (!enclosingInfo.isConstructor())
  956. return null;
  957. ConstructorRepository typeInfo = ConstructorRepository.make(enclosingInfo.getDescriptor(),
  958. getFactory());
  959. Type [] parameterTypes = typeInfo.getParameterTypes();
  960. Class<?>[] parameterClasses = new Class<?>[parameterTypes.length];
  961. // Convert Types to Classes; returned types *should*
  962. // be class objects since the methodDescriptor's used
  963. // don't have generics information
  964. for(int i = 0; i < parameterClasses.length; i++)
  965. parameterClasses[i] = toClass(parameterTypes[i]);
  966. /*
  967. * Loop over all declared constructors; match number
  968. * of and type of parameters.
  969. */
  970. for(Constructor<?> c: enclosingInfo.getEnclosingClass().getDeclaredConstructors()) {
  971. Class<?>[] candidateParamClasses = c.getParameterTypes();
  972. if (candidateParamClasses.length == parameterClasses.length) {
  973. boolean matches = true;
  974. for(int i = 0; i < candidateParamClasses.length; i++) {
  975. if (!candidateParamClasses[i].equals(parameterClasses[i])) {
  976. matches = false;
  977. break;
  978. }
  979. }
  980. if (matches)
  981. return c;
  982. }
  983. }
  984. throw new InternalError("Enclosing constructor not found");
  985. }
  986. }
  987. /**
  988. * If the class or interface represented by this {@code Class} object
  989. * is a member of another class, returns the {@code Class} object
  990. * representing the class in which it was declared. This method returns
  991. * null if this class or interface is not a member of any other class. If
  992. * this {@code Class} object represents an array class, a primitive
  993. * type, or void,then this method returns null.
  994. *
  995. * @return the declaring class for this class
  996. * @since JDK1.1
  997. */
  998. public native Class<?> getDeclaringClass();
  999. /**
  1000. * Returns the immediately enclosing class of the underlying
  1001. * class. If the underlying class is a top level class this
  1002. * method returns {@code null}.
  1003. * @return the immediately enclosing class of the underlying class
  1004. * @since 1.5
  1005. */
  1006. public Class<?> getEnclosingClass() {
  1007. // There are five kinds of classes (or interfaces):
  1008. // a) Top level classes
  1009. // b) Nested classes (static member classes)
  1010. // c) Inner classes (non-static member classes)
  1011. // d) Local classes (named classes declared within a method)
  1012. // e) Anonymous classes
  1013. // JVM Spec 4.8.6: A class must have an EnclosingMethod
  1014. // attribute if and only if it is a local class or an
  1015. // anonymous class.
  1016. EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
  1017. if (enclosingInfo == null) {
  1018. // This is a top level or a nested class or an inner class (a, b, or c)
  1019. return getDeclaringClass();
  1020. } else {
  1021. Class<?> enclosingClass = enclosingInfo.getEnclosingClass();
  1022. // This is a local class or an anonymous class (d or e)
  1023. if (enclosingClass == this || enclosingClass == null)
  1024. throw new InternalError("Malformed enclosing method information");
  1025. else
  1026. return enclosingClass;
  1027. }
  1028. }
  1029. /**
  1030. * Returns the simple name of the underlying class as given in the
  1031. * source code. Returns an empty string if the underlying class is
  1032. * anonymous.
  1033. *
  1034. * <p>The simple name of an array is the simple name of the
  1035. * component type with "[]" appended. In particular the simple
  1036. * name of an array whose component type is anonymous is "[]".
  1037. *
  1038. * @return the simple name of the underlying class
  1039. * @since 1.5
  1040. */
  1041. public String getSimpleName() {
  1042. if (isArray())
  1043. return getComponentType().getSimpleName()+"[]";
  1044. String simpleName = getSimpleBinaryName();
  1045. if (simpleName == null) { // top level class
  1046. simpleName = getName();
  1047. return simpleName.substring(simpleName.lastIndexOf(".")+1); // strip the package name
  1048. }
  1049. // According to JLS3 "Binary Compatibility" (13.1) the binary
  1050. // name of non-package classes (not top level) is the binary
  1051. // name of the immediately enclosing class followed by a '$' followed by:
  1052. // (for nested and inner classes): the simple name.
  1053. // (for local classes): 1 or more digits followed by the simple name.
  1054. // (for anonymous classes): 1 or more digits.
  1055. // Since getSimpleBinaryName() will strip the binary name of
  1056. // the immediatly enclosing class, we are now looking at a
  1057. // string that matches the regular expression "\$[0-9]*"
  1058. // followed by a simple name (considering the simple of an
  1059. // anonymous class to be the empty string).
  1060. // Remove leading "\$[0-9]*" from the name
  1061. int length = simpleName.length();
  1062. if (length < 1 || simpleName.charAt(0) != '$')
  1063. throw new InternalError("Malformed class name");
  1064. int index = 1;
  1065. while (index < length && isAsciiDigit(simpleName.charAt(index)))
  1066. index++;
  1067. // Eventually, this is the empty string iff this is an anonymous class
  1068. return simpleName.substring(index);
  1069. }
  1070. /**
  1071. * Character.isDigit answers {@code true} to some non-ascii
  1072. * digits. This one does not.
  1073. */
  1074. private static boolean isAsciiDigit(char c) {
  1075. return '0' <= c && c <= '9';
  1076. }
  1077. /**
  1078. * Returns the canonical name of the underlying class as
  1079. * defined by the Java Language Specification. Returns null if
  1080. * the underlying class does not have a canonical name (i.e., if
  1081. * it is a local or anonymous class or an array whose component
  1082. * type does not have a canonical name).
  1083. * @return the canonical name of the underlying class if it exists, and
  1084. * {@code null} otherwise.
  1085. * @since 1.5
  1086. */
  1087. public String getCanonicalName() {
  1088. if (isArray()) {
  1089. String canonicalName = getComponentType().getCanonicalName();
  1090. if (canonicalName != null)
  1091. return canonicalName + "[]";
  1092. else
  1093. return null;
  1094. }
  1095. if (isLocalOrAnonymousClass())
  1096. return null;
  1097. Class<?> enclosingClass = getEnclosingClass();
  1098. if (enclosingClass == nul

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