PageRenderTime 61ms CodeModel.GetById 30ms RepoModel.GetById 0ms app.codeStats 1ms

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

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

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