PageRenderTime 59ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

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

https://bitbucket.org/psandoz/lambda-jdk
Java | 3126 lines | 1118 code | 236 blank | 1772 comment | 337 complexity | 20ef9ef5e0e17d13786fa1abfba38261 MD5 | raw file
Possible License(s): BSD-3-Clause-No-Nuclear-License-2014, LGPL-3.0, GPL-2.0
  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 {
  1098. String enclosingName = enclosingClass.getCanonicalName();
  1099. if (enclosingName == null)
  1100. return null;
  1101. return enclosingName + "." + getSimpleName();
  1102. }
  1103. }
  1104. /**
  1105. * Returns {@code true} if and only if the underlying class
  1106. * is an anonymous class.
  1107. *
  1108. * @return {@code true} if and only if this class is an anonymous class.
  1109. * @since 1.5
  1110. */
  1111. public boolean isAnonymousClass() {
  1112. return "".equals(getSimpleName());
  1113. }
  1114. /**
  1115. * Returns {@code true} if and only if the underlying class
  1116. * is a local class.
  1117. *
  1118. * @return {@code true} if and only if this class is a local class.
  1119. * @since 1.5
  1120. */
  1121. public boolean isLocalClass() {
  1122. return isLocalOrAnonymousClass() && !isAnonymousClass();
  1123. }
  1124. /**
  1125. * Returns {@code true} if and only if the underlying class
  1126. * is a member class.
  1127. *
  1128. * @return {@code true} if and only if this class is a member class.
  1129. * @since 1.5
  1130. */
  1131. public boolean isMemberClass() {
  1132. return getSimpleBinaryName() != null && !isLocalOrAnonymousClass();
  1133. }
  1134. /**
  1135. * Returns the "simple binary name" of the underlying class, i.e.,
  1136. * the binary name without the leading enclosing class name.
  1137. * Returns {@code null} if the underlying class is a top level
  1138. * class.
  1139. */
  1140. private String getSimpleBinaryName() {
  1141. Class<?> enclosingClass = getEnclosingClass();
  1142. if (enclosingClass == null) // top level class
  1143. return null;
  1144. // Otherwise, strip the enclosing class' name
  1145. try {
  1146. return getName().substring(enclosingClass.getName().length());
  1147. } catch (IndexOutOfBoundsException ex) {
  1148. throw new InternalError("Malformed class name", ex);
  1149. }
  1150. }
  1151. /**
  1152. * Returns {@code true} if this is a local class or an anonymous
  1153. * class. Returns {@code false} otherwise.
  1154. */
  1155. private boolean isLocalOrAnonymousClass() {
  1156. // JVM Spec 4.8.6: A class must have an EnclosingMethod
  1157. // attribute if and only if it is a local class or an
  1158. // anonymous class.
  1159. return getEnclosingMethodInfo() != null;
  1160. }
  1161. /**
  1162. * Returns an array containing {@code Class} objects representing all
  1163. * the public classes and interfaces that are members of the class
  1164. * represented by this {@code Class} object. This includes public
  1165. * class and interface members inherited from superclasses and public class
  1166. * and interface members declared by the class. This method returns an
  1167. * array of length 0 if this {@code Class} object has no public member
  1168. * classes or interfaces. This method also returns an array of length 0 if
  1169. * this {@code Class} object represents a primitive type, an array
  1170. * class, or void.
  1171. *
  1172. * @return the array of {@code Class} objects representing the public
  1173. * members of this class
  1174. * @exception SecurityException
  1175. * If a security manager, <i>s</i>, is present and any of the
  1176. * following conditions is met:
  1177. *
  1178. * <ul>
  1179. *
  1180. * <li> invocation of
  1181. * {@link SecurityManager#checkMemberAccess
  1182. * s.checkMemberAccess(this, Member.PUBLIC)} method
  1183. * denies access to the classes within this class
  1184. *
  1185. * <li> the caller's class loader is not the same as or an
  1186. * ancestor of the class loader for the current class and
  1187. * invocation of {@link SecurityManager#checkPackageAccess
  1188. * s.checkPackageAccess()} denies access to the package
  1189. * of this class
  1190. *
  1191. * </ul>
  1192. *
  1193. * @since JDK1.1
  1194. */
  1195. public Class<?>[] getClasses() {
  1196. // be very careful not to change the stack depth of this
  1197. // checkMemberAccess call for security reasons
  1198. // see java.lang.SecurityManager.checkMemberAccess
  1199. checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader());
  1200. // Privileged so this implementation can look at DECLARED classes,
  1201. // something the caller might not have privilege to do. The code here
  1202. // is allowed to look at DECLARED classes because (1) it does not hand
  1203. // out anything other than public members and (2) public member access
  1204. // has already been ok'd by the SecurityManager.
  1205. return java.security.AccessController.doPrivileged(
  1206. new java.security.PrivilegedAction<Class<?>[]>() {
  1207. public Class<?>[] run() {
  1208. List<Class<?>> list = new ArrayList<>();
  1209. Class<?> currentClass = Class.this;
  1210. while (currentClass != null) {
  1211. Class<?>[] members = currentClass.getDeclaredClasses();
  1212. for (int i = 0; i < members.length; i++) {
  1213. if (Modifier.isPublic(members[i].getModifiers())) {
  1214. list.add(members[i]);
  1215. }
  1216. }
  1217. currentClass = currentClass.getSuperclass();
  1218. }
  1219. return list.toArray(new Class<?>[0]);
  1220. }
  1221. });
  1222. }
  1223. /**
  1224. * Returns an array containing {@code Field} objects reflecting all
  1225. * the accessible public fields of the class or interface represented by
  1226. * this {@code Class} object. The elements in the array returned are
  1227. * not sorted and are not in any particular order. This method returns an
  1228. * array of length 0 if the class or interface has no accessible public
  1229. * fields, or if it represents an array class, a primitive type, or void.
  1230. *
  1231. * <p> Specifically, if this {@code Class} object represents a class,
  1232. * this method returns the public fields of this class and of all its
  1233. * superclasses. If this {@code Class} object represents an
  1234. * interface, this method returns the fields of this interface and of all
  1235. * its superinterfaces.
  1236. *
  1237. * <p> The implicit length field for array class is not reflected by this
  1238. * method. User code should use the methods of class {@code Array} to
  1239. * manipulate arrays.
  1240. *
  1241. * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3.
  1242. *
  1243. * @return the array of {@code Field} objects representing the
  1244. * public fields
  1245. * @exception SecurityException
  1246. * If a security manager, <i>s</i>, is present and any of the
  1247. * following conditions is met:
  1248. *
  1249. * <ul>
  1250. *
  1251. * <li> invocation of
  1252. * {@link SecurityManager#checkMemberAccess
  1253. * s.checkMemberAccess(this, Member.PUBLIC)} denies
  1254. * access to the fields within this class
  1255. *
  1256. * <li> the caller's class loader is not the same as or an
  1257. * ancestor of the class loader for the current class and
  1258. * invocation of {@link SecurityManager#checkPackageAccess
  1259. * s.checkPackageAccess()} denies access to the package
  1260. * of this class
  1261. *
  1262. * </ul>
  1263. *
  1264. * @since JDK1.1
  1265. */
  1266. public Field[] getFields() throws SecurityException {
  1267. // be very careful not to change the stack depth of this
  1268. // checkMemberAccess call for security reasons
  1269. // see java.lang.SecurityManager.checkMemberAccess
  1270. checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader());
  1271. return copyFields(privateGetPublicFields(null));
  1272. }
  1273. /**
  1274. * Returns an array containing {@code Method} objects reflecting all
  1275. * the public <em>member</em> methods of the class or interface represented
  1276. * by this {@code Class} object, including those declared by the class
  1277. * or interface and those inherited from superclasses and
  1278. * superinterfaces. Array classes return all the (public) member methods
  1279. * inherited from the {@code Object} class. The elements in the array
  1280. * returned are not sorted and are not in any particular order. This
  1281. * method returns an array of length 0 if this {@code Class} object
  1282. * represents a class or interface that has no public member methods, or if
  1283. * this {@code Class} object represents a primitive type or void.
  1284. *
  1285. * <p> The class initialization method {@code <clinit>} is not
  1286. * included in the returned array. If the class declares multiple public
  1287. * member methods with the same parameter types, they are all included in
  1288. * the returned array.
  1289. *
  1290. * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.4.
  1291. *
  1292. * @return the array of {@code Method} objects representing the
  1293. * public methods of this class
  1294. * @exception SecurityException
  1295. * If a security manager, <i>s</i>, is present and any of the
  1296. * following conditions is met:
  1297. *
  1298. * <ul>
  1299. *
  1300. * <li> invocation of
  1301. * {@link SecurityManager#checkMemberAccess
  1302. * s.checkMemberAccess(this, Member.PUBLIC)} denies
  1303. * access to the methods within this class
  1304. *
  1305. * <li> the caller's class loader is not the same as or an
  1306. * ancestor of the class loader for the current class and
  1307. * invocation of {@link SecurityManager#checkPackageAccess
  1308. * s.checkPackageAccess()} denies access to the package
  1309. * of this class
  1310. *
  1311. * </ul>
  1312. *
  1313. * @since JDK1.1
  1314. */
  1315. public Method[] getMethods() throws SecurityException {
  1316. // be very careful not to change the stack depth of this
  1317. // checkMemberAccess call for security reasons
  1318. // see java.lang.SecurityManager.checkMemberAccess
  1319. checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader());
  1320. return copyMethods(privateGetPublicMethods());
  1321. }
  1322. /**
  1323. * Returns an array containing {@code Constructor} objects reflecting
  1324. * all the public constructors of the class represented by this
  1325. * {@code Class} object. An array of length 0 is returned if the
  1326. * class has no public constructors, or if the class is an array class, or
  1327. * if the class reflects a primitive type or void.
  1328. *
  1329. * Note that while this method returns an array of {@code
  1330. * Constructor<T>} objects (that is an array of constructors from
  1331. * this class), the return type of this method is {@code
  1332. * Constructor<?>[]} and <em>not</em> {@code Constructor<T>[]} as
  1333. * might be expected. This less informative return type is
  1334. * necessary since after being returned from this method, the
  1335. * array could be modified to hold {@code Constructor} objects for
  1336. * different classes, which would violate the type guarantees of
  1337. * {@code Constructor<T>[]}.
  1338. *
  1339. * @return the array of {@code Constructor} objects representing the
  1340. * public constructors of this class
  1341. * @exception SecurityException
  1342. * If a security manager, <i>s</i>, is present and any of the
  1343. * following conditions is met:
  1344. *
  1345. * <ul>
  1346. *
  1347. * <li> invocation of
  1348. * {@link SecurityManager#checkMemberAccess
  1349. * s.checkMemberAccess(this, Member.PUBLIC)} denies
  1350. * access to the constructors within this class
  1351. *
  1352. * <li> the caller's class loader is not the same as or an
  1353. * ancestor of the class loader for the current class and
  1354. * invocation of {@link SecurityManager#checkPackageAccess
  1355. * s.checkPackageAccess()} denies access to the package
  1356. * of this class
  1357. *
  1358. * </ul>
  1359. *
  1360. * @since JDK1.1
  1361. */
  1362. public Constructor<?>[] getConstructors() throws SecurityException {
  1363. // be very careful not to change the stack depth of this
  1364. // checkMemberAccess call for security reasons
  1365. // see java.lang.SecurityManager.checkMemberAccess
  1366. checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader());
  1367. return copyConstructors(privateGetDeclaredConstructors(true));
  1368. }
  1369. /**
  1370. * Returns a {@code Field} object that reflects the specified public
  1371. * member field of the class or interface represented by this
  1372. * {@code Class} object. The {@code name} parameter is a
  1373. * {@code String} specifying the simple name of the desired field.
  1374. *
  1375. * <p> The field to be reflected is determined by the algorithm that
  1376. * follows. Let C be the class represented by this object:
  1377. * <OL>
  1378. * <LI> If C declares a public field with the name specified, that is the
  1379. * field to be reflected.</LI>
  1380. * <LI> If no field was found in step 1 above, this algorithm is applied
  1381. * recursively to each direct superinterface of C. The direct
  1382. * superinterfaces are searched in the order they were declared.</LI>
  1383. * <LI> If no field was found in steps 1 and 2 above, and C has a
  1384. * superclass S, then this algorithm is invoked recursively upon S.
  1385. * If C has no superclass, then a {@code NoSuchFieldException}
  1386. * is thrown.</LI>
  1387. * </OL>
  1388. *
  1389. * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3.
  1390. *
  1391. * @param name the field name
  1392. * @return the {@code Field} object of this class specified by
  1393. * {@code name}
  1394. * @exception NoSuchFieldException if a field with the specified name is
  1395. * not found.
  1396. * @exception NullPointerException if {@code name} is {@code null}
  1397. * @exception SecurityException
  1398. * If a security manager, <i>s</i>, is present and any of the
  1399. * following conditions is met:
  1400. *
  1401. * <ul>
  1402. *
  1403. * <li> invocation of
  1404. * {@link SecurityManager#checkMemberAccess
  1405. * s.checkMemberAccess(this, Member.PUBLIC)} denies
  1406. * access to the field
  1407. *
  1408. * <li> the caller's class loader is not the same as or an
  1409. * ancestor of the class loader for the current class and
  1410. * invocation of {@link SecurityManager#checkPackageAccess
  1411. * s.checkPackageAccess()} denies access to the package
  1412. * of this class
  1413. *
  1414. * </ul>
  1415. *
  1416. * @since JDK1.1
  1417. */
  1418. public Field getField(String name)
  1419. throws NoSuchFieldException, SecurityException {
  1420. // be very careful not to change the stack depth of this
  1421. // checkMemberAccess call for security reasons
  1422. // see java.lang.SecurityManager.checkMemberAccess
  1423. checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader());
  1424. Field field = getField0(name);
  1425. if (field == null) {
  1426. throw new NoSuchFieldException(name);
  1427. }
  1428. return field;
  1429. }
  1430. /**
  1431. * Returns a {@code Method} object that reflects the specified public
  1432. * member method of the class or interface represented by this
  1433. * {@code Class} object. The {@code name} parameter is a
  1434. * {@code String} specifying the simple name of the desired method. The
  1435. * {@code parameterTypes} parameter is an array of {@code Class}
  1436. * objects that identify the method's formal parameter types, in declared
  1437. * order. If {@code parameterTypes} is {@code null}, it is
  1438. * treated as if it were an empty array.
  1439. *
  1440. * <p> If the {@code name} is "{@code <init>};"or "{@code <clinit>}" a
  1441. * {@code NoSuchMethodException} is raised. Otherwise, the method to
  1442. * be reflected is determined by the algorithm that follows. Let C be the
  1443. * class represented by this object:
  1444. * <OL>
  1445. * <LI> C is searched for any <I>matching methods</I>. If no matching
  1446. * method is found, the algorithm of step 1 is invoked recursively on
  1447. * the superclass of C.</LI>
  1448. * <LI> If no method was found in step 1 above, the superinterfaces of C
  1449. * are searched for a matching method. If any such method is found, it
  1450. * is reflected.</LI>
  1451. * </OL>
  1452. *
  1453. * To find a matching method in a class C:&nbsp; If C declares exactly one
  1454. * public method with the specified name and exactly the same formal
  1455. * parameter types, that is the method reflected. If more than one such
  1456. * method is found in C, and one of these methods has a return type that is
  1457. * more specific than any of the others, that method is reflected;
  1458. * otherwise one of the methods is chosen arbitrarily.
  1459. *
  1460. * <p>Note that there may be more than one matching method in a
  1461. * class because while the Java language forbids a class to
  1462. * declare multiple methods with the same signature but different
  1463. * return types, the Java virtual machine does not. This
  1464. * increased flexibility in the virtual machine can be used to
  1465. * implement various language features. For example, covariant
  1466. * returns can be implemented with {@linkplain
  1467. * java.lang.reflect.Method#isBridge bridge methods}; the bridge
  1468. * method and the method being overridden would have the same
  1469. * signature but different return types.
  1470. *
  1471. * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.4.
  1472. *
  1473. * @param name the name of the method
  1474. * @param parameterTypes the list of parameters
  1475. * @return the {@code Method} object that matches the specified
  1476. * {@code name} and {@code parameterTypes}
  1477. * @exception NoSuchMethodException if a matching method is not found
  1478. * or if the name is "&lt;init&gt;"or "&lt;clinit&gt;".
  1479. * @exception NullPointerException if {@code name} is {@code null}
  1480. * @exception SecurityException
  1481. * If a security manager, <i>s</i>, is present and any of the
  1482. * following conditions is met:
  1483. *
  1484. * <ul>
  1485. *
  1486. * <li> invocation of
  1487. * {@link SecurityManager#checkMemberAccess
  1488. * s.checkMemberAccess(this, Member.PUBLIC)} denies
  1489. * access to the method
  1490. *
  1491. * <li> the caller's class loader is not the same as or an
  1492. * ancestor of the class loader for the current class and
  1493. * invocation of {@link SecurityManager#checkPackageAccess
  1494. * s.checkPackageAccess()} denies access to the package
  1495. * of this class
  1496. *
  1497. * </ul>
  1498. *
  1499. * @since JDK1.1
  1500. */
  1501. public Method getMethod(String name, Class<?>... parameterTypes)
  1502. throws NoSuchMethodException, SecurityException {
  1503. // be very careful not to change the stack depth of this
  1504. // checkMemberAccess call for security reasons
  1505. // see java.lang.SecurityManager.checkMemberAccess
  1506. checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader());
  1507. Method method = getMethod0(name, parameterTypes);
  1508. if (method == null) {
  1509. throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes));
  1510. }
  1511. return method;
  1512. }
  1513. /**
  1514. * Returns a {@code Constructor} object that reflects the specified
  1515. * public constructor of the class represented by this {@code Class}
  1516. * object. The {@code parameterTypes} parameter is an array of
  1517. * {@code Class} objects that identify the constructor's formal
  1518. * parameter types, in declared order.
  1519. *
  1520. * If this {@code Class} object represents an inner class
  1521. * declared in a non-static context, the formal parameter types
  1522. * include the explicit enclosing instance as the first parameter.
  1523. *
  1524. * <p> The constructor to reflect is the public constructor of the class
  1525. * represented by this {@code Class} object whose formal parameter
  1526. * types match those specified by {@code parameterTypes}.
  1527. *
  1528. * @param parameterTypes the parameter array
  1529. * @return the {@code Constructor} object of the public constructor that
  1530. * matches the specified {@code parameterTypes}
  1531. * @exception NoSuchMethodException if a matching method is not found.
  1532. * @exception SecurityException
  1533. * If a security manager, <i>s</i>, is present and any of the
  1534. * following conditions is met:
  1535. *
  1536. * <ul>
  1537. *
  1538. * <li> invocation of
  1539. * {@link SecurityManager#checkMemberAccess
  1540. * s.checkMemberAccess(this, Member.PUBLIC)} denies
  1541. * access to the constructor
  1542. *
  1543. * <li> the caller's class loader is not the same as or an
  1544. * ancestor of the class loader for the current class and
  1545. * invocation of {@link SecurityManager#checkPackageAccess
  1546. * s.checkPackageAccess()} denies access to the package
  1547. * of this class
  1548. *
  1549. * </ul>
  1550. *
  1551. * @since JDK1.1
  1552. */
  1553. public Constructor<T> getConstructor(Class<?>... parameterTypes)
  1554. throws NoSuchMethodException, SecurityException {
  1555. // be very careful not to change the stack depth of this
  1556. // checkMemberAccess call for security reasons
  1557. // see java.lang.SecurityManager.checkMemberAccess
  1558. checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader());
  1559. return getConstructor0(parameterTypes, Member.PUBLIC);
  1560. }
  1561. /**
  1562. * Returns an array of {@code Class} objects reflecting all the
  1563. * classes and interfaces declared as members of the class represented by
  1564. * this {@code Class} object. This includes public, protected, default
  1565. * (package) access, and private classes and interfaces declared by the
  1566. * class, but excludes inherited classes and interfaces. This method
  1567. * returns an array of length 0 if the class declares no classes or
  1568. * interfaces as members, or if this {@code Class} object represents a
  1569. * primitive type, an array class, or void.
  1570. *
  1571. * @return the array of {@code Class} objects representing all the
  1572. * declared members of this class
  1573. * @exception SecurityException
  1574. * If a security manager, <i>s</i>, is present and any of the
  1575. * following conditions is met:
  1576. *
  1577. * <ul>
  1578. *
  1579. * <li> invocation of
  1580. * {@link SecurityManager#checkMemberAccess
  1581. * s.checkMemberAccess(this, Member.DECLARED)} denies
  1582. * access to the declared classes within this class
  1583. *
  1584. * <li> the caller's class loader is not the same as or an
  1585. * ancestor of the class loader for the current class and
  1586. * invocation of {@link SecurityManager#checkPackageAccess
  1587. * s.checkPackageAccess()} denies access to the package
  1588. * of this class
  1589. *
  1590. * </ul>
  1591. *
  1592. * @since JDK1.1
  1593. */
  1594. public Class<?>[] getDeclaredClasses() throws SecurityException {
  1595. // be very careful not to change the stack depth of this
  1596. // checkMemberAccess call for security reasons
  1597. // see java.lang.SecurityManager.checkMemberAccess
  1598. checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader());
  1599. return getDeclaredClasses0();
  1600. }
  1601. /**
  1602. * Returns an array of {@code Field} objects reflecting all the fields
  1603. * declared by the class or interface represented by this
  1604. * {@code Class} object. This includes public, protected, default
  1605. * (package) access, and private fields, but excludes inherited fields.
  1606. * The elements in the array returned are not sorted and are not in any
  1607. * particular order. This method returns an array of length 0 if the class
  1608. * or interface declares no fields, or if this {@code Class} object
  1609. * represents a primitive type, an array class, or void.
  1610. *
  1611. * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3.
  1612. *
  1613. * @return the array of {@code Field} objects representing all the
  1614. * declared fields of this class
  1615. * @exception SecurityException
  1616. * If a security manager, <i>s</i>, is present and any of the
  1617. * following conditions is met:
  1618. *
  1619. * <ul>
  1620. *
  1621. * <li> invocation of
  1622. * {@link SecurityManager#checkMemberAccess
  1623. * s.checkMemberAccess(this, Member.DECLARED)} denies
  1624. * access to the declared fields within this class
  1625. *
  1626. * <li> the caller's class loader is not the same as or an
  1627. * ancestor of the class loader for the current class and
  1628. * invocation of {@link SecurityManager#checkPackageAccess
  1629. * s.checkPackageAccess()} denies access to the package
  1630. * of this class
  1631. *
  1632. * </ul>
  1633. *
  1634. * @since JDK1.1
  1635. */
  1636. public Field[] getDeclaredFields() throws SecurityException {
  1637. // be very careful not to change the stack depth of this
  1638. // checkMemberAccess call for security reasons
  1639. // see java.lang.SecurityManager.checkMemberAccess
  1640. checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader());
  1641. return copyFields(privateGetDeclaredFields(false));
  1642. }
  1643. /**
  1644. * Returns an array of {@code Method} objects reflecting all the
  1645. * methods declared by the class or interface represented by this
  1646. * {@code Class} object. This includes public, protected, default
  1647. * (package) access, and private methods, but excludes inherited methods.
  1648. * The elements in the array returned are not sorted and are not in any
  1649. * particular order. This method returns an array of length 0 if the class
  1650. * or interface declares no methods, or if this {@code Class} object
  1651. * represents a primitive type, an array class, or void. The class
  1652. * initialization method {@code <clinit>} is not included in the
  1653. * returned array. If the class declares multiple public member methods
  1654. * with the same parameter types, they are all included in the returned
  1655. * array.
  1656. *
  1657. * <p> See <em>The Java Language Specification</em>, section 8.2.
  1658. *
  1659. * @return the array of {@code Method} objects representing all the
  1660. * declared methods of this class
  1661. * @exception SecurityException
  1662. * If a security manager, <i>s</i>, is present and any of the
  1663. * following conditions is met:
  1664. *
  1665. * <ul>
  1666. *
  1667. * <li> invocation of
  1668. * {@link SecurityManager#checkMemberAccess
  1669. * s.checkMemberAccess(this, Member.DECLARED)} denies
  1670. * access to the declared methods within this class
  1671. *
  1672. * <li> the caller's class loader is not the same as or an
  1673. * ancestor of the class loader for the current class and
  1674. * invocation of {@link SecurityManager#checkPackageAccess
  1675. * s.checkPackageAccess()} denies access to the package
  1676. * of this class
  1677. *
  1678. * </ul>
  1679. *
  1680. * @since JDK1.1
  1681. */
  1682. public Method[] getDeclaredMethods() throws SecurityException {
  1683. // be very careful not to change the stack depth of this
  1684. // checkMemberAccess call for security reasons
  1685. // see java.lang.SecurityManager.checkMemberAccess
  1686. checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader());
  1687. return copyMethods(privateGetDeclaredMethods(false));
  1688. }
  1689. /**
  1690. * Returns an array of {@code Constructor} objects reflecting all the
  1691. * constructors declared by the class represented by this
  1692. * {@code Class} object. These are public, protected, default
  1693. * (package) access, and private constructors. The elements in the array
  1694. * returned are not sorted and are not in any particular order. If the
  1695. * class has a default constructor, it is included in the returned array.
  1696. * This method returns an array of length 0 if this {@code Class}
  1697. * object represents an interface, a primitive type, an array class, or
  1698. * void.
  1699. *
  1700. * <p> See <em>The Java Language Specification</em>, section 8.2.
  1701. *
  1702. * @return the array of {@code Constructor} objects representing all the
  1703. * declared constructors of this class
  1704. * @exception SecurityException
  1705. * If a security manager, <i>s</i>, is present and any of the
  1706. * following conditions is met:
  1707. *
  1708. * <ul>
  1709. *
  1710. * <li> invocation of
  1711. * {@link SecurityManager#checkMemberAccess
  1712. * s.checkMemberAccess(this, Member.DECLARED)} denies
  1713. * access to the declared constructors within this class
  1714. *
  1715. * <li> the caller's class loader is not the same as or an
  1716. * ancestor of the class loader for the current class and
  1717. * invocation of {@link SecurityManager#checkPackageAccess
  1718. * s.checkPackageAccess()} denies access to the package
  1719. * of this class
  1720. *
  1721. * </ul>
  1722. *
  1723. * @since JDK1.1
  1724. */
  1725. public Constructor<?>[] getDeclaredConstructors() throws SecurityException {
  1726. // be very careful not to change the stack depth of this
  1727. // checkMemberAccess call for security reasons
  1728. // see java.lang.SecurityManager.checkMemberAccess
  1729. checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader());
  1730. return copyConstructors(privateGetDeclaredConstructors(false));
  1731. }
  1732. /**
  1733. * Returns a {@code Field} object that reflects the specified declared
  1734. * field of the class or interface represented by this {@code Class}
  1735. * object. The {@code name} parameter is a {@code String} that
  1736. * specifies the simple name of the desired field. Note that this method
  1737. * will not reflect the {@code length} field of an array class.
  1738. *
  1739. * @param name the name of the field
  1740. * @return the {@code Field} object for the specified field in this
  1741. * class
  1742. * @exception NoSuchFieldException if a field with the specified name is
  1743. * not found.
  1744. * @exception NullPointerException if {@code name} is {@code null}
  1745. * @exception SecurityException
  1746. * If a security manager, <i>s</i>, is present and any of the
  1747. * following conditions is met:
  1748. *
  1749. * <ul>
  1750. *
  1751. * <li> invocation of
  1752. * {@link SecurityManager#checkMemberAccess
  1753. * s.checkMemberAccess(this, Member.DECLARED)} denies
  1754. * access to the declared field
  1755. *
  1756. * <li> the caller's class loader is not the same as or an
  1757. * ancestor of the class loader for the current class and
  1758. * invocation of {@link SecurityManager#checkPackageAccess
  1759. * s.checkPackageAccess()} denies access to the package
  1760. * of this class
  1761. *
  1762. * </ul>
  1763. *
  1764. * @since JDK1.1
  1765. */
  1766. public Field getDeclaredField(String name)
  1767. throws NoSuchFieldException, SecurityException {
  1768. // be very careful not to change the stack depth of this
  1769. // checkMemberAccess call for security reasons
  1770. // see java.lang.SecurityManager.checkMemberAccess
  1771. checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader());
  1772. Field field = searchFields(privateGetDeclaredFields(false), name);
  1773. if (field == null) {
  1774. throw new NoSuchFieldException(name);
  1775. }
  1776. return field;
  1777. }
  1778. /**
  1779. * Returns a {@code Method} object that reflects the specified
  1780. * declared method of the class or interface represented by this
  1781. * {@code Class} object. The {@code name} parameter is a
  1782. * {@code String} that specifies the simple name of the desired
  1783. * method, and the {@code parameterTypes} parameter is an array of
  1784. * {@code Class} objects that identify the method's formal parameter
  1785. * types, in declared order. If more than one method with the same
  1786. * parameter types is declared in a class, and one of these methods has a
  1787. * return type that is more specific than any of the others, that method is
  1788. * returned; otherwise one of the methods is chosen arbitrarily. If the
  1789. * name is "&lt;init&gt;"or "&lt;clinit&gt;" a {@code NoSuchMethodException}
  1790. * is raised.
  1791. *
  1792. * @param name the name of the method
  1793. * @param parameterTypes the parameter array
  1794. * @return the {@code Method} object for the method of this class
  1795. * matching the specified name and parameters
  1796. * @exception NoSuchMethodException if a matching method is not found.
  1797. * @exception NullPointerException if {@code name} is {@code null}
  1798. * @exception SecurityException
  1799. * If a security manager, <i>s</i>, is present and any of the
  1800. * following conditions is met:
  1801. *
  1802. * <ul>
  1803. *
  1804. * <li> invocation of
  1805. * {@link SecurityManager#checkMemberAccess
  1806. * s.checkMemberAccess(this, Member.DECLARED)} denies
  1807. * access to the declared method
  1808. *
  1809. * <li> the caller's class loader is not the same as or an
  1810. * ancestor of the class loader for the current class and
  1811. * invocation of {@link SecurityManager#checkPackageAccess
  1812. * s.checkPackageAccess()} denies access to the package
  1813. * of this class
  1814. *
  1815. * </ul>
  1816. *
  1817. * @since JDK1.1
  1818. */
  1819. public Method getDeclaredMethod(String name, Class<?>... parameterTypes)
  1820. throws NoSuchMethodException, SecurityException {
  1821. // be very careful not to change the stack depth of this
  1822. // checkMemberAccess call for security reasons
  1823. // see java.lang.SecurityManager.checkMemberAccess
  1824. checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader());
  1825. Method method = searchMethods(privateGetDeclaredMethods(false), name, parameterTypes);
  1826. if (method == null) {
  1827. throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes));
  1828. }
  1829. return method;
  1830. }
  1831. /**
  1832. * Returns a {@code Constructor} object that reflects the specified
  1833. * constructor of the class or interface represented by this
  1834. * {@code Class} object. The {@code parameterTypes} parameter is
  1835. * an array of {@code Class} objects that identify the constructor's
  1836. * formal parameter types, in declared order.
  1837. *
  1838. * If this {@code Class} object represents an inner class
  1839. * declared in a non-static context, the formal parameter types
  1840. * include the explicit enclosing instance as the first parameter.
  1841. *
  1842. * @param parameterTypes the parameter array
  1843. * @return The {@code Constructor} object for the constructor with the
  1844. * specified parameter list
  1845. * @exception NoSuchMethodException if a matching method is not found.
  1846. * @exception SecurityException
  1847. * If a security manager, <i>s</i>, is present and any of the
  1848. * following conditions is met:
  1849. *
  1850. * <ul>
  1851. *
  1852. * <li> invocation of
  1853. * {@link SecurityManager#checkMemberAccess
  1854. * s.checkMemberAccess(this, Member.DECLARED)} denies
  1855. * access to the declared constructor
  1856. *
  1857. * <li> the caller's class loader is not the same as or an
  1858. * ancestor of the class loader for the current class and
  1859. * invocation of {@link SecurityManager#checkPackageAccess
  1860. * s.checkPackageAccess()} denies access to the package
  1861. * of this class
  1862. *
  1863. * </ul>
  1864. *
  1865. * @since JDK1.1
  1866. */
  1867. public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)
  1868. throws NoSuchMethodException, SecurityException {
  1869. // be very careful not to change the stack depth of this
  1870. // checkMemberAccess call for security reasons
  1871. // see java.lang.SecurityManager.checkMemberAccess
  1872. checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader());
  1873. return getConstructor0(parameterTypes, Member.DECLARED);
  1874. }
  1875. /**
  1876. * Finds a resource with a given name. The rules for searching resources
  1877. * associated with a given class are implemented by the defining
  1878. * {@linkplain ClassLoader class loader} of the class. This method
  1879. * delegates to this object's class loader. If this object was loaded by
  1880. * the bootstrap class loader, the method delegates to {@link
  1881. * ClassLoader#getSystemResourceAsStream}.
  1882. *
  1883. * <p> Before delegation, an absolute resource name is constructed from the
  1884. * given resource name using this algorithm:
  1885. *
  1886. * <ul>
  1887. *
  1888. * <li> If the {@code name} begins with a {@code '/'}
  1889. * (<tt>'&#92;u002f'</tt>), then the absolute name of the resource is the
  1890. * portion of the {@code name} following the {@code '/'}.
  1891. *
  1892. * <li> Otherwise, the absolute name is of the following form:
  1893. *
  1894. * <blockquote>
  1895. * {@code modified_package_name/name}
  1896. * </blockquote>
  1897. *
  1898. * <p> Where the {@code modified_package_name} is the package name of this
  1899. * object with {@code '/'} substituted for {@code '.'}
  1900. * (<tt>'&#92;u002e'</tt>).
  1901. *
  1902. * </ul>
  1903. *
  1904. * @param name name of the desired resource
  1905. * @return A {@link java.io.InputStream} object or {@code null} if
  1906. * no resource with this name is found
  1907. * @throws NullPointerException If {@code name} is {@code null}
  1908. * @since JDK1.1
  1909. */
  1910. public InputStream getResourceAsStream(String name) {
  1911. name = resolveName(name);
  1912. ClassLoader cl = getClassLoader0();
  1913. if (cl==null) {
  1914. // A system class.
  1915. return ClassLoader.getSystemResourceAsStream(name);
  1916. }
  1917. return cl.getResourceAsStream(name);
  1918. }
  1919. /**
  1920. * Finds a resource with a given name. The rules for searching resources
  1921. * associated with a given class are implemented by the defining
  1922. * {@linkplain ClassLoader class loader} of the class. This method
  1923. * delegates to this object's class loader. If this object was loaded by
  1924. * the bootstrap class loader, the method delegates to {@link
  1925. * ClassLoader#getSystemResource}.
  1926. *
  1927. * <p> Before delegation, an absolute resource name is constructed from the
  1928. * given resource name using this algorithm:
  1929. *
  1930. * <ul>
  1931. *
  1932. * <li> If the {@code name} begins with a {@code '/'}
  1933. * (<tt>'&#92;u002f'</tt>), then the absolute name of the resource is the
  1934. * portion of the {@code name} following the {@code '/'}.
  1935. *
  1936. * <li> Otherwise, the absolute name is of the following form:
  1937. *
  1938. * <blockquote>
  1939. * {@code modified_package_name/name}
  1940. * </blockquote>
  1941. *
  1942. * <p> Where the {@code modified_package_name} is the package name of this
  1943. * object with {@code '/'} substituted for {@code '.'}
  1944. * (<tt>'&#92;u002e'</tt>).
  1945. *
  1946. * </ul>
  1947. *
  1948. * @param name name of the desired resource
  1949. * @return A {@link java.net.URL} object or {@code null} if no
  1950. * resource with this name is found
  1951. * @since JDK1.1
  1952. */
  1953. public java.net.URL getResource(String name) {
  1954. name = resolveName(name);
  1955. ClassLoader cl = getClassLoader0();
  1956. if (cl==null) {
  1957. // A system class.
  1958. return ClassLoader.getSystemResource(name);
  1959. }
  1960. return cl.getResource(name);
  1961. }
  1962. /** protection domain returned when the internal domain is null */
  1963. private static java.security.ProtectionDomain allPermDomain;
  1964. /**
  1965. * Returns the {@code ProtectionDomain} of this class. If there is a
  1966. * security manager installed, this method first calls the security
  1967. * manager's {@code checkPermission} method with a
  1968. * {@code RuntimePermission("getProtectionDomain")} permission to
  1969. * ensure it's ok to get the
  1970. * {@code ProtectionDomain}.
  1971. *
  1972. * @return the ProtectionDomain of this class
  1973. *
  1974. * @throws SecurityException
  1975. * if a security manager exists and its
  1976. * {@code checkPermission} method doesn't allow
  1977. * getting the ProtectionDomain.
  1978. *
  1979. * @see java.security.ProtectionDomain
  1980. * @see SecurityManager#checkPermission
  1981. * @see java.lang.RuntimePermission
  1982. * @since 1.2
  1983. */
  1984. public java.security.ProtectionDomain getProtectionDomain() {
  1985. SecurityManager sm = System.getSecurityManager();
  1986. if (sm != null) {
  1987. sm.checkPermission(SecurityConstants.GET_PD_PERMISSION);
  1988. }
  1989. java.security.ProtectionDomain pd = getProtectionDomain0();
  1990. if (pd == null) {
  1991. if (allPermDomain == null) {
  1992. java.security.Permissions perms =
  1993. new java.security.Permissions();
  1994. perms.add(SecurityConstants.ALL_PERMISSION);
  1995. allPermDomain =
  1996. new java.security.ProtectionDomain(null, perms);
  1997. }
  1998. pd = allPermDomain;
  1999. }
  2000. return pd;
  2001. }
  2002. /**
  2003. * Returns the ProtectionDomain of this class.
  2004. */
  2005. private native java.security.ProtectionDomain getProtectionDomain0();
  2006. /**
  2007. * Set the ProtectionDomain for this class. Called by
  2008. * ClassLoader.defineClass.
  2009. */
  2010. native void setProtectionDomain0(java.security.ProtectionDomain pd);
  2011. /*
  2012. * Return the Virtual Machine's Class object for the named
  2013. * primitive type.
  2014. */
  2015. static native Class<?> getPrimitiveClass(String name);
  2016. /*
  2017. * Check if client is allowed to access members. If access is denied,
  2018. * throw a SecurityException.
  2019. *
  2020. * Be very careful not to change the stack depth of this checkMemberAccess
  2021. * call for security reasons.
  2022. * See java.lang.SecurityManager.checkMemberAccess.
  2023. *
  2024. * <p> Default policy: allow all clients access with normal Java access
  2025. * control.
  2026. */
  2027. private void checkMemberAccess(int which, ClassLoader ccl) {
  2028. SecurityManager s = System.getSecurityManager();
  2029. if (s != null) {
  2030. s.checkMemberAccess(this, which);
  2031. ClassLoader cl = getClassLoader0();
  2032. if ((ccl != null) && (ccl != cl) &&
  2033. ((cl == null) || !cl.isAncestor(ccl))) {
  2034. String name = this.getName();
  2035. int i = name.lastIndexOf('.');
  2036. if (i != -1) {
  2037. s.checkPackageAccess(name.substring(0, i));
  2038. }
  2039. }
  2040. }
  2041. }
  2042. /**
  2043. * Add a package name prefix if the name is not absolute Remove leading "/"
  2044. * if name is absolute
  2045. */
  2046. private String resolveName(String name) {
  2047. if (name == null) {
  2048. return name;
  2049. }
  2050. if (!name.startsWith("/")) {
  2051. Class<?> c = this;
  2052. while (c.isArray()) {
  2053. c = c.getComponentType();
  2054. }
  2055. String baseName = c.getName();
  2056. int index = baseName.lastIndexOf('.');
  2057. if (index != -1) {
  2058. name = baseName.substring(0, index).replace('.', '/')
  2059. +"/"+name;
  2060. }
  2061. } else {
  2062. name = name.substring(1);
  2063. }
  2064. return name;
  2065. }
  2066. /**
  2067. * Reflection support.
  2068. */
  2069. // Caches for certain reflective results
  2070. private static boolean useCaches = true;
  2071. private volatile transient SoftReference<Field[]> declaredFields;
  2072. private volatile transient SoftReference<Field[]> publicFields;
  2073. private volatile transient SoftReference<Method[]> declaredMethods;
  2074. private volatile transient SoftReference<Method[]> publicMethods;
  2075. private volatile transient SoftReference<Constructor<T>[]> declaredConstructors;
  2076. private volatile transient SoftReference<Constructor<T>[]> publicConstructors;
  2077. // Intermediate results for getFields and getMethods
  2078. private volatile transient SoftReference<Field[]> declaredPublicFields;
  2079. private volatile transient SoftReference<Method[]> declaredPublicMethods;
  2080. // Incremented by the VM on each call to JVM TI RedefineClasses()
  2081. // that redefines this class or a superclass.
  2082. private volatile transient int classRedefinedCount = 0;
  2083. // Value of classRedefinedCount when we last cleared the cached values
  2084. // that are sensitive to class redefinition.
  2085. private volatile transient int lastRedefinedCount = 0;
  2086. // Clears cached values that might possibly have been obsoleted by
  2087. // a class redefinition.
  2088. private void clearCachesOnClassRedefinition() {
  2089. if (lastRedefinedCount != classRedefinedCount) {
  2090. declaredFields = publicFields = declaredPublicFields = null;
  2091. declaredMethods = publicMethods = declaredPublicMethods = null;
  2092. declaredConstructors = publicConstructors = null;
  2093. annotations = declaredAnnotations = null;
  2094. // Use of "volatile" (and synchronization by caller in the case
  2095. // of annotations) ensures that no thread sees the update to
  2096. // lastRedefinedCount before seeing the caches cleared.
  2097. // We do not guard against brief windows during which multiple
  2098. // threads might redundantly work to fill an empty cache.
  2099. lastRedefinedCount = classRedefinedCount;
  2100. }
  2101. }
  2102. // Generic signature handling
  2103. private native String getGenericSignature();
  2104. // Generic info repository; lazily initialized
  2105. private transient ClassRepository genericInfo;
  2106. // accessor for factory
  2107. private GenericsFactory getFactory() {
  2108. // create scope and factory
  2109. return CoreReflectionFactory.make(this, ClassScope.make(this));
  2110. }
  2111. // accessor for generic info repository
  2112. private ClassRepository getGenericInfo() {
  2113. // lazily initialize repository if necessary
  2114. if (genericInfo == null) {
  2115. // create and cache generic info repository
  2116. genericInfo = ClassRepository.make(getGenericSignature(),
  2117. getFactory());
  2118. }
  2119. return genericInfo; //return cached repository
  2120. }
  2121. // Annotations handling
  2122. private native byte[] getRawAnnotations();
  2123. native ConstantPool getConstantPool();
  2124. //
  2125. //
  2126. // java.lang.reflect.Field handling
  2127. //
  2128. //
  2129. // Returns an array of "root" fields. These Field objects must NOT
  2130. // be propagated to the outside world, but must instead be copied
  2131. // via ReflectionFactory.copyField.
  2132. private Field[] privateGetDeclaredFields(boolean publicOnly) {
  2133. checkInitted();
  2134. Field[] res = null;
  2135. if (useCaches) {
  2136. clearCachesOnClassRedefinition();
  2137. if (publicOnly) {
  2138. if (declaredPublicFields != null) {
  2139. res = declaredPublicFields.get();
  2140. }
  2141. } else {
  2142. if (declaredFields != null) {
  2143. res = declaredFields.get();
  2144. }
  2145. }
  2146. if (res != null) return res;
  2147. }
  2148. // No cached value available; request value from VM
  2149. res = Reflection.filterFields(this, getDeclaredFields0(publicOnly));
  2150. if (useCaches) {
  2151. if (publicOnly) {
  2152. declaredPublicFields = new SoftReference<>(res);
  2153. } else {
  2154. declaredFields = new SoftReference<>(res);
  2155. }
  2156. }
  2157. return res;
  2158. }
  2159. // Returns an array of "root" fields. These Field objects must NOT
  2160. // be propagated to the outside world, but must instead be copied
  2161. // via ReflectionFactory.copyField.
  2162. private Field[] privateGetPublicFields(Set<Class<?>> traversedInterfaces) {
  2163. checkInitted();
  2164. Field[] res = null;
  2165. if (useCaches) {
  2166. clearCachesOnClassRedefinition();
  2167. if (publicFields != null) {
  2168. res = publicFields.get();
  2169. }
  2170. if (res != null) return res;
  2171. }
  2172. // No cached value available; compute value recursively.
  2173. // Traverse in correct order for getField().
  2174. List<Field> fields = new ArrayList<>();
  2175. if (traversedInterfaces == null) {
  2176. traversedInterfaces = new HashSet<>();
  2177. }
  2178. // Local fields
  2179. Field[] tmp = privateGetDeclaredFields(true);
  2180. addAll(fields, tmp);
  2181. // Direct superinterfaces, recursively
  2182. for (Class<?> c : getInterfaces()) {
  2183. if (!traversedInterfaces.contains(c)) {
  2184. traversedInterfaces.add(c);
  2185. addAll(fields, c.privateGetPublicFields(traversedInterfaces));
  2186. }
  2187. }
  2188. // Direct superclass, recursively
  2189. if (!isInterface()) {
  2190. Class<?> c = getSuperclass();
  2191. if (c != null) {
  2192. addAll(fields, c.privateGetPublicFields(traversedInterfaces));
  2193. }
  2194. }
  2195. res = new Field[fields.size()];
  2196. fields.toArray(res);
  2197. if (useCaches) {
  2198. publicFields = new SoftReference<>(res);
  2199. }
  2200. return res;
  2201. }
  2202. private static void addAll(Collection<Field> c, Field[] o) {
  2203. for (int i = 0; i < o.length; i++) {
  2204. c.add(o[i]);
  2205. }
  2206. }
  2207. //
  2208. //
  2209. // java.lang.reflect.Constructor handling
  2210. //
  2211. //
  2212. // Returns an array of "root" constructors. These Constructor
  2213. // objects must NOT be propagated to the outside world, but must
  2214. // instead be copied via ReflectionFactory.copyConstructor.
  2215. private Constructor<T>[] privateGetDeclaredConstructors(boolean publicOnly) {
  2216. checkInitted();
  2217. Constructor<T>[] res = null;
  2218. if (useCaches) {
  2219. clearCachesOnClassRedefinition();
  2220. if (publicOnly) {
  2221. if (publicConstructors != null) {
  2222. res = publicConstructors.get();
  2223. }
  2224. } else {
  2225. if (declaredConstructors != null) {
  2226. res = declaredConstructors.get();
  2227. }
  2228. }
  2229. if (res != null) return res;
  2230. }
  2231. // No cached value available; request value from VM
  2232. if (isInterface()) {
  2233. @SuppressWarnings("unchecked")
  2234. Constructor<T>[] temporaryRes = (Constructor<T>[]) new Constructor<?>[0];
  2235. res = temporaryRes;
  2236. } else {
  2237. res = getDeclaredConstructors0(publicOnly);
  2238. }
  2239. if (useCaches) {
  2240. if (publicOnly) {
  2241. publicConstructors = new SoftReference<>(res);
  2242. } else {
  2243. declaredConstructors = new SoftReference<>(res);
  2244. }
  2245. }
  2246. return res;
  2247. }
  2248. //
  2249. //
  2250. // java.lang.reflect.Method handling
  2251. //
  2252. //
  2253. // Returns an array of "root" methods. These Method objects must NOT
  2254. // be propagated to the outside world, but must instead be copied
  2255. // via ReflectionFactory.copyMethod.
  2256. private Method[] privateGetDeclaredMethods(boolean publicOnly) {
  2257. checkInitted();
  2258. Method[] res = null;
  2259. if (useCaches) {
  2260. clearCachesOnClassRedefinition();
  2261. if (publicOnly) {
  2262. if (declaredPublicMethods != null) {
  2263. res = declaredPublicMethods.get();
  2264. }
  2265. } else {
  2266. if (declaredMethods != null) {
  2267. res = declaredMethods.get();
  2268. }
  2269. }
  2270. if (res != null) return res;
  2271. }
  2272. // No cached value available; request value from VM
  2273. res = Reflection.filterMethods(this, getDeclaredMethods0(publicOnly));
  2274. if (useCaches) {
  2275. if (publicOnly) {
  2276. declaredPublicMethods = new SoftReference<>(res);
  2277. } else {
  2278. declaredMethods = new SoftReference<>(res);
  2279. }
  2280. }
  2281. return res;
  2282. }
  2283. static class MethodArray {
  2284. private Method[] methods;
  2285. private int length;
  2286. MethodArray() {
  2287. methods = new Method[20];
  2288. length = 0;
  2289. }
  2290. void add(Method m) {
  2291. if (length == methods.length) {
  2292. methods = Arrays.copyOf(methods, 2 * methods.length);
  2293. }
  2294. methods[length++] = m;
  2295. }
  2296. void addAll(Method[] ma) {
  2297. for (int i = 0; i < ma.length; i++) {
  2298. add(ma[i]);
  2299. }
  2300. }
  2301. void addAll(MethodArray ma) {
  2302. for (int i = 0; i < ma.length(); i++) {
  2303. add(ma.get(i));
  2304. }
  2305. }
  2306. void addIfNotPresent(Method newMethod) {
  2307. for (int i = 0; i < length; i++) {
  2308. Method m = methods[i];
  2309. if (m == newMethod || (m != null && m.equals(newMethod))) {
  2310. return;
  2311. }
  2312. }
  2313. add(newMethod);
  2314. }
  2315. void addAllIfNotPresent(MethodArray newMethods) {
  2316. for (int i = 0; i < newMethods.length(); i++) {
  2317. Method m = newMethods.get(i);
  2318. if (m != null) {
  2319. addIfNotPresent(m);
  2320. }
  2321. }
  2322. }
  2323. int length() {
  2324. return length;
  2325. }
  2326. Method get(int i) {
  2327. return methods[i];
  2328. }
  2329. void removeByNameAndSignature(Method toRemove) {
  2330. for (int i = 0; i < length; i++) {
  2331. Method m = methods[i];
  2332. if (m != null &&
  2333. m.getReturnType() == toRemove.getReturnType() &&
  2334. m.getName() == toRemove.getName() &&
  2335. arrayContentsEq(m.getParameterTypes(),
  2336. toRemove.getParameterTypes())) {
  2337. methods[i] = null;
  2338. }
  2339. }
  2340. }
  2341. void compactAndTrim() {
  2342. int newPos = 0;
  2343. // Get rid of null slots
  2344. for (int pos = 0; pos < length; pos++) {
  2345. Method m = methods[pos];
  2346. if (m != null) {
  2347. if (pos != newPos) {
  2348. methods[newPos] = m;
  2349. }
  2350. newPos++;
  2351. }
  2352. }
  2353. if (newPos != methods.length) {
  2354. methods = Arrays.copyOf(methods, newPos);
  2355. }
  2356. }
  2357. Method[] getArray() {
  2358. return methods;
  2359. }
  2360. }
  2361. // Returns an array of "root" methods. These Method objects must NOT
  2362. // be propagated to the outside world, but must instead be copied
  2363. // via ReflectionFactory.copyMethod.
  2364. private Method[] privateGetPublicMethods() {
  2365. checkInitted();
  2366. Method[] res = null;
  2367. if (useCaches) {
  2368. clearCachesOnClassRedefinition();
  2369. if (publicMethods != null) {
  2370. res = publicMethods.get();
  2371. }
  2372. if (res != null) return res;
  2373. }
  2374. // No cached value available; compute value recursively.
  2375. // Start by fetching public declared methods
  2376. MethodArray methods = new MethodArray();
  2377. {
  2378. Method[] tmp = privateGetDeclaredMethods(true);
  2379. methods.addAll(tmp);
  2380. }
  2381. // Now recur over superclass and direct superinterfaces.
  2382. // Go over superinterfaces first so we can more easily filter
  2383. // out concrete implementations inherited from superclasses at
  2384. // the end.
  2385. MethodArray inheritedMethods = new MethodArray();
  2386. Class<?>[] interfaces = getInterfaces();
  2387. for (int i = 0; i < interfaces.length; i++) {
  2388. inheritedMethods.addAll(interfaces[i].privateGetPublicMethods());
  2389. }
  2390. if (!isInterface()) {
  2391. Class<?> c = getSuperclass();
  2392. if (c != null) {
  2393. MethodArray supers = new MethodArray();
  2394. supers.addAll(c.privateGetPublicMethods());
  2395. // Filter out concrete implementations of any
  2396. // interface methods
  2397. for (int i = 0; i < supers.length(); i++) {
  2398. Method m = supers.get(i);
  2399. if (m != null && !Modifier.isAbstract(m.getModifiers())) {
  2400. inheritedMethods.removeByNameAndSignature(m);
  2401. }
  2402. }
  2403. // Insert superclass's inherited methods before
  2404. // superinterfaces' to satisfy getMethod's search
  2405. // order
  2406. supers.addAll(inheritedMethods);
  2407. inheritedMethods = supers;
  2408. }
  2409. }
  2410. // Filter out all local methods from inherited ones
  2411. for (int i = 0; i < methods.length(); i++) {
  2412. Method m = methods.get(i);
  2413. inheritedMethods.removeByNameAndSignature(m);
  2414. }
  2415. methods.addAllIfNotPresent(inheritedMethods);
  2416. methods.compactAndTrim();
  2417. res = methods.getArray();
  2418. if (useCaches) {
  2419. publicMethods = new SoftReference<>(res);
  2420. }
  2421. return res;
  2422. }
  2423. //
  2424. // Helpers for fetchers of one field, method, or constructor
  2425. //
  2426. private Field searchFields(Field[] fields, String name) {
  2427. String internedName = name.intern();
  2428. for (int i = 0; i < fields.length; i++) {
  2429. if (fields[i].getName() == internedName) {
  2430. return getReflectionFactory().copyField(fields[i]);
  2431. }
  2432. }
  2433. return null;
  2434. }
  2435. private Field getField0(String name) throws NoSuchFieldException {
  2436. // Note: the intent is that the search algorithm this routine
  2437. // uses be equivalent to the ordering imposed by
  2438. // privateGetPublicFields(). It fetches only the declared
  2439. // public fields for each class, however, to reduce the number
  2440. // of Field objects which have to be created for the common
  2441. // case where the field being requested is declared in the
  2442. // class which is being queried.
  2443. Field res = null;
  2444. // Search declared public fields
  2445. if ((res = searchFields(privateGetDeclaredFields(true), name)) != null) {
  2446. return res;
  2447. }
  2448. // Direct superinterfaces, recursively
  2449. Class<?>[] interfaces = getInterfaces();
  2450. for (int i = 0; i < interfaces.length; i++) {
  2451. Class<?> c = interfaces[i];
  2452. if ((res = c.getField0(name)) != null) {
  2453. return res;
  2454. }
  2455. }
  2456. // Direct superclass, recursively
  2457. if (!isInterface()) {
  2458. Class<?> c = getSuperclass();
  2459. if (c != null) {
  2460. if ((res = c.getField0(name)) != null) {
  2461. return res;
  2462. }
  2463. }
  2464. }
  2465. return null;
  2466. }
  2467. private static Method searchMethods(Method[] methods,
  2468. String name,
  2469. Class<?>[] parameterTypes)
  2470. {
  2471. Method res = null;
  2472. String internedName = name.intern();
  2473. for (int i = 0; i < methods.length; i++) {
  2474. Method m = methods[i];
  2475. if (m.getName() == internedName
  2476. && arrayContentsEq(parameterTypes, m.getParameterTypes())
  2477. && (res == null
  2478. || res.getReturnType().isAssignableFrom(m.getReturnType())))
  2479. res = m;
  2480. }
  2481. return (res == null ? res : getReflectionFactory().copyMethod(res));
  2482. }
  2483. private Method getMethod0(String name, Class<?>[] parameterTypes) {
  2484. // Note: the intent is that the search algorithm this routine
  2485. // uses be equivalent to the ordering imposed by
  2486. // privateGetPublicMethods(). It fetches only the declared
  2487. // public methods for each class, however, to reduce the
  2488. // number of Method objects which have to be created for the
  2489. // common case where the method being requested is declared in
  2490. // the class which is being queried.
  2491. Method res = null;
  2492. // Search declared public methods
  2493. if ((res = searchMethods(privateGetDeclaredMethods(true),
  2494. name,
  2495. parameterTypes)) != null) {
  2496. return res;
  2497. }
  2498. // Search superclass's methods
  2499. if (!isInterface()) {
  2500. Class<? super T> c = getSuperclass();
  2501. if (c != null) {
  2502. if ((res = c.getMethod0(name, parameterTypes)) != null) {
  2503. return res;
  2504. }
  2505. }
  2506. }
  2507. // Search superinterfaces' methods
  2508. Class<?>[] interfaces = getInterfaces();
  2509. for (int i = 0; i < interfaces.length; i++) {
  2510. Class<?> c = interfaces[i];
  2511. if ((res = c.getMethod0(name, parameterTypes)) != null) {
  2512. return res;
  2513. }
  2514. }
  2515. // Not found
  2516. return null;
  2517. }
  2518. private Constructor<T> getConstructor0(Class<?>[] parameterTypes,
  2519. int which) throws NoSuchMethodException
  2520. {
  2521. Constructor<T>[] constructors = privateGetDeclaredConstructors((which == Member.PUBLIC));
  2522. for (Constructor<T> constructor : constructors) {
  2523. if (arrayContentsEq(parameterTypes,
  2524. constructor.getParameterTypes())) {
  2525. return getReflectionFactory().copyConstructor(constructor);
  2526. }
  2527. }
  2528. throw new NoSuchMethodException(getName() + ".<init>" + argumentTypesToString(parameterTypes));
  2529. }
  2530. //
  2531. // Other helpers and base implementation
  2532. //
  2533. private static boolean arrayContentsEq(Object[] a1, Object[] a2) {
  2534. if (a1 == null) {
  2535. return a2 == null || a2.length == 0;
  2536. }
  2537. if (a2 == null) {
  2538. return a1.length == 0;
  2539. }
  2540. if (a1.length != a2.length) {
  2541. return false;
  2542. }
  2543. for (int i = 0; i < a1.length; i++) {
  2544. if (a1[i] != a2[i]) {
  2545. return false;
  2546. }
  2547. }
  2548. return true;
  2549. }
  2550. private static Field[] copyFields(Field[] arg) {
  2551. Field[] out = new Field[arg.length];
  2552. ReflectionFactory fact = getReflectionFactory();
  2553. for (int i = 0; i < arg.length; i++) {
  2554. out[i] = fact.copyField(arg[i]);
  2555. }
  2556. return out;
  2557. }
  2558. private static Method[] copyMethods(Method[] arg) {
  2559. Method[] out = new Method[arg.length];
  2560. ReflectionFactory fact = getReflectionFactory();
  2561. for (int i = 0; i < arg.length; i++) {
  2562. out[i] = fact.copyMethod(arg[i]);
  2563. }
  2564. return out;
  2565. }
  2566. private static <U> Constructor<U>[] copyConstructors(Constructor<U>[] arg) {
  2567. Constructor<U>[] out = arg.clone();
  2568. ReflectionFactory fact = getReflectionFactory();
  2569. for (int i = 0; i < out.length; i++) {
  2570. out[i] = fact.copyConstructor(out[i]);
  2571. }
  2572. return out;
  2573. }
  2574. private native Field[] getDeclaredFields0(boolean publicOnly);
  2575. private native Method[] getDeclaredMethods0(boolean publicOnly);
  2576. private native Constructor<T>[] getDeclaredConstructors0(boolean publicOnly);
  2577. private native Class<?>[] getDeclaredClasses0();
  2578. private static String argumentTypesToString(Class<?>[] argTypes) {
  2579. StringBuilder buf = new StringBuilder();
  2580. buf.append("(");
  2581. if (argTypes != null) {
  2582. for (int i = 0; i < argTypes.length; i++) {
  2583. if (i > 0) {
  2584. buf.append(", ");
  2585. }
  2586. Class<?> c = argTypes[i];
  2587. buf.append((c == null) ? "null" : c.getName());
  2588. }
  2589. }
  2590. buf.append(")");
  2591. return buf.toString();
  2592. }
  2593. /** use serialVersionUID from JDK 1.1 for interoperability */
  2594. private static final long serialVersionUID = 3206093459760846163L;
  2595. /**
  2596. * Class Class is special cased within the Serialization Stream Protocol.
  2597. *
  2598. * A Class instance is written initially into an ObjectOutputStream in the
  2599. * following format:
  2600. * <pre>
  2601. * {@code TC_CLASS} ClassDescriptor
  2602. * A ClassDescriptor is a special cased serialization of
  2603. * a {@code java.io.ObjectStreamClass} instance.
  2604. * </pre>
  2605. * A new handle is generated for the initial time the class descriptor
  2606. * is written into the stream. Future references to the class descriptor
  2607. * are written as references to the initial class descriptor instance.
  2608. *
  2609. * @see java.io.ObjectStreamClass
  2610. */
  2611. private static final ObjectStreamField[] serialPersistentFields =
  2612. new ObjectStreamField[0];
  2613. /**
  2614. * Returns the assertion status that would be assigned to this
  2615. * class if it were to be initialized at the time this method is invoked.
  2616. * If this class has had its assertion status set, the most recent
  2617. * setting will be returned; otherwise, if any package default assertion
  2618. * status pertains to this class, the most recent setting for the most
  2619. * specific pertinent package default assertion status is returned;
  2620. * otherwise, if this class is not a system class (i.e., it has a
  2621. * class loader) its class loader's default assertion status is returned;
  2622. * otherwise, the system class default assertion status is returned.
  2623. * <p>
  2624. * Few programmers will have any need for this method; it is provided
  2625. * for the benefit of the JRE itself. (It allows a class to determine at
  2626. * the time that it is initialized whether assertions should be enabled.)
  2627. * Note that this method is not guaranteed to return the actual
  2628. * assertion status that was (or will be) associated with the specified
  2629. * class when it was (or will be) initialized.
  2630. *
  2631. * @return the desired assertion status of the specified class.
  2632. * @see java.lang.ClassLoader#setClassAssertionStatus
  2633. * @see java.lang.ClassLoader#setPackageAssertionStatus
  2634. * @see java.lang.ClassLoader#setDefaultAssertionStatus
  2635. * @since 1.4
  2636. */
  2637. public boolean desiredAssertionStatus() {
  2638. ClassLoader loader = getClassLoader();
  2639. // If the loader is null this is a system class, so ask the VM
  2640. if (loader == null)
  2641. return desiredAssertionStatus0(this);
  2642. // If the classloader has been initialized with the assertion
  2643. // directives, ask it. Otherwise, ask the VM.
  2644. synchronized(loader.assertionLock) {
  2645. if (loader.classAssertionStatus != null) {
  2646. return loader.desiredAssertionStatus(getName());
  2647. }
  2648. }
  2649. return desiredAssertionStatus0(this);
  2650. }
  2651. // Retrieves the desired assertion status of this class from the VM
  2652. private static native boolean desiredAssertionStatus0(Class<?> clazz);
  2653. /**
  2654. * Returns true if and only if this class was declared as an enum in the
  2655. * source code.
  2656. *
  2657. * @return true if and only if this class was declared as an enum in the
  2658. * source code
  2659. * @since 1.5
  2660. */
  2661. public boolean isEnum() {
  2662. // An enum must both directly extend java.lang.Enum and have
  2663. // the ENUM bit set; classes for specialized enum constants
  2664. // don't do the former.
  2665. return (this.getModifiers() & ENUM) != 0 &&
  2666. this.getSuperclass() == java.lang.Enum.class;
  2667. }
  2668. // Fetches the factory for reflective objects
  2669. private static ReflectionFactory getReflectionFactory() {
  2670. if (reflectionFactory == null) {
  2671. reflectionFactory =
  2672. java.security.AccessController.doPrivileged
  2673. (new sun.reflect.ReflectionFactory.GetReflectionFactoryAction());
  2674. }
  2675. return reflectionFactory;
  2676. }
  2677. private static ReflectionFactory reflectionFactory;
  2678. // To be able to query system properties as soon as they're available
  2679. private static boolean initted = false;
  2680. private static void checkInitted() {
  2681. if (initted) return;
  2682. AccessController.doPrivileged(new PrivilegedAction<Void>() {
  2683. public Void run() {
  2684. // Tests to ensure the system properties table is fully
  2685. // initialized. This is needed because reflection code is
  2686. // called very early in the initialization process (before
  2687. // command-line arguments have been parsed and therefore
  2688. // these user-settable properties installed.) We assume that
  2689. // if System.out is non-null then the System class has been
  2690. // fully initialized and that the bulk of the startup code
  2691. // has been run.
  2692. if (System.out == null) {
  2693. // java.lang.System not yet fully initialized
  2694. return null;
  2695. }
  2696. // Doesn't use Boolean.getBoolean to avoid class init.
  2697. String val =
  2698. System.getProperty("sun.reflect.noCaches");
  2699. if (val != null && val.equals("true")) {
  2700. useCaches = false;
  2701. }
  2702. initted = true;
  2703. return null;
  2704. }
  2705. });
  2706. }
  2707. /**
  2708. * Returns the elements of this enum class or null if this
  2709. * Class object does not represent an enum type.
  2710. *
  2711. * @return an array containing the values comprising the enum class
  2712. * represented by this Class object in the order they're
  2713. * declared, or null if this Class object does not
  2714. * represent an enum type
  2715. * @since 1.5
  2716. */
  2717. public T[] getEnumConstants() {
  2718. T[] values = getEnumConstantsShared();
  2719. return (values != null) ? values.clone() : null;
  2720. }
  2721. /**
  2722. * Returns the elements of this enum class or null if this
  2723. * Class object does not represent an enum type;
  2724. * identical to getEnumConstants except that the result is
  2725. * uncloned, cached, and shared by all callers.
  2726. */
  2727. T[] getEnumConstantsShared() {
  2728. if (enumConstants == null) {
  2729. if (!isEnum()) return null;
  2730. try {
  2731. final Method values = getMethod("values");
  2732. java.security.AccessController.doPrivileged(
  2733. new java.security.PrivilegedAction<Void>() {
  2734. public Void run() {
  2735. values.setAccessible(true);
  2736. return null;
  2737. }
  2738. });
  2739. @SuppressWarnings("unchecked")
  2740. T[] temporaryConstants = (T[])values.invoke(null);
  2741. enumConstants = temporaryConstants;
  2742. }
  2743. // These can happen when users concoct enum-like classes
  2744. // that don't comply with the enum spec.
  2745. catch (InvocationTargetException | NoSuchMethodException |
  2746. IllegalAccessException ex) { return null; }
  2747. }
  2748. return enumConstants;
  2749. }
  2750. private volatile transient T[] enumConstants = null;
  2751. /**
  2752. * Returns a map from simple name to enum constant. This package-private
  2753. * method is used internally by Enum to implement
  2754. * public static <T extends Enum<T>> T valueOf(Class<T>, String)
  2755. * efficiently. Note that the map is returned by this method is
  2756. * created lazily on first use. Typically it won't ever get created.
  2757. */
  2758. Map<String, T> enumConstantDirectory() {
  2759. if (enumConstantDirectory == null) {
  2760. T[] universe = getEnumConstantsShared();
  2761. if (universe == null)
  2762. throw new IllegalArgumentException(
  2763. getName() + " is not an enum type");
  2764. Map<String, T> m = new HashMap<>(2 * universe.length);
  2765. for (T constant : universe)
  2766. m.put(((Enum<?>)constant).name(), constant);
  2767. enumConstantDirectory = m;
  2768. }
  2769. return enumConstantDirectory;
  2770. }
  2771. private volatile transient Map<String, T> enumConstantDirectory = null;
  2772. /**
  2773. * Casts an object to the class or interface represented
  2774. * by this {@code Class} object.
  2775. *
  2776. * @param obj the object to be cast
  2777. * @return the object after casting, or null if obj is null
  2778. *
  2779. * @throws ClassCastException if the object is not
  2780. * null and is not assignable to the type T.
  2781. *
  2782. * @since 1.5
  2783. */
  2784. @SuppressWarnings("unchecked")
  2785. public T cast(Object obj) {
  2786. if (obj != null && !isInstance(obj))
  2787. throw new ClassCastException(cannotCastMsg(obj));
  2788. return (T) obj;
  2789. }
  2790. private String cannotCastMsg(Object obj) {
  2791. return "Cannot cast " + obj.getClass().getName() + " to " + getName();
  2792. }
  2793. /**
  2794. * Casts this {@code Class} object to represent a subclass of the class
  2795. * represented by the specified class object. Checks that the cast
  2796. * is valid, and throws a {@code ClassCastException} if it is not. If
  2797. * this method succeeds, it always returns a reference to this class object.
  2798. *
  2799. * <p>This method is useful when a client needs to "narrow" the type of
  2800. * a {@code Class} object to pass it to an API that restricts the
  2801. * {@code Class} objects that it is willing to accept. A cast would
  2802. * generate a compile-time warning, as the correctness of the cast
  2803. * could not be checked at runtime (because generic types are implemented
  2804. * by erasure).
  2805. *
  2806. * @return this {@code Class} object, cast to represent a subclass of
  2807. * the specified class object.
  2808. * @throws ClassCastException if this {@code Class} object does not
  2809. * represent a subclass of the specified class (here "subclass" includes
  2810. * the class itself).
  2811. * @since 1.5
  2812. */
  2813. @SuppressWarnings("unchecked")
  2814. public <U> Class<? extends U> asSubclass(Class<U> clazz) {
  2815. if (clazz.isAssignableFrom(this))
  2816. return (Class<? extends U>) this;
  2817. else
  2818. throw new ClassCastException(this.toString());
  2819. }
  2820. /**
  2821. * @throws NullPointerException {@inheritDoc}
  2822. * @since 1.5
  2823. */
  2824. @SuppressWarnings("unchecked")
  2825. public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {
  2826. if (annotationClass == null)
  2827. throw new NullPointerException();
  2828. initAnnotationsIfNecessary();
  2829. return (A) annotations.get(annotationClass);
  2830. }
  2831. /**
  2832. * @throws NullPointerException {@inheritDoc}
  2833. * @since 1.5
  2834. */
  2835. public boolean isAnnotationPresent(
  2836. Class<? extends Annotation> annotationClass) {
  2837. if (annotationClass == null)
  2838. throw new NullPointerException();
  2839. return getAnnotation(annotationClass) != null;
  2840. }
  2841. /**
  2842. * @since 1.5
  2843. */
  2844. public Annotation[] getAnnotations() {
  2845. initAnnotationsIfNecessary();
  2846. return AnnotationParser.toArray(annotations);
  2847. }
  2848. /**
  2849. * @since 1.5
  2850. */
  2851. public Annotation[] getDeclaredAnnotations() {
  2852. initAnnotationsIfNecessary();
  2853. return AnnotationParser.toArray(declaredAnnotations);
  2854. }
  2855. // Annotations cache
  2856. private transient Map<Class<? extends Annotation>, Annotation> annotations;
  2857. private transient Map<Class<? extends Annotation>, Annotation> declaredAnnotations;
  2858. private synchronized void initAnnotationsIfNecessary() {
  2859. clearCachesOnClassRedefinition();
  2860. if (annotations != null)
  2861. return;
  2862. declaredAnnotations = AnnotationParser.parseAnnotations(
  2863. getRawAnnotations(), getConstantPool(), this);
  2864. Class<?> superClass = getSuperclass();
  2865. if (superClass == null) {
  2866. annotations = declaredAnnotations;
  2867. } else {
  2868. annotations = new HashMap<>();
  2869. superClass.initAnnotationsIfNecessary();
  2870. for (Map.Entry<Class<? extends Annotation>, Annotation> e : superClass.annotations.entrySet()) {
  2871. Class<? extends Annotation> annotationClass = e.getKey();
  2872. if (AnnotationType.getInstance(annotationClass).isInherited())
  2873. annotations.put(annotationClass, e.getValue());
  2874. }
  2875. annotations.putAll(declaredAnnotations);
  2876. }
  2877. }
  2878. // Annotation types cache their internal (AnnotationType) form
  2879. private AnnotationType annotationType;
  2880. void setAnnotationType(AnnotationType type) {
  2881. annotationType = type;
  2882. }
  2883. AnnotationType getAnnotationType() {
  2884. return annotationType;
  2885. }
  2886. /* Backing store of user-defined values pertaining to this class.
  2887. * Maintained by the ClassValue class.
  2888. */
  2889. transient ClassValue.ClassValueMap classValueMap;
  2890. }