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

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

https://bitbucket.org/weijun/jdk8-tl-jdk
Java | 3113 lines | 1109 code | 235 blank | 1769 comment | 337 complexity | a14dcee421cbaec3f7550d5dc01c6275 MD5 | raw file
Possible License(s): GPL-2.0, BSD-3-Clause-No-Nuclear-License-2014, LGPL-3.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. public TypeVariable<Class<T>>[] getTypeParameters() {
  602. if (getGenericSignature() != null)
  603. return (TypeVariable<Class<T>>[])getGenericInfo().getTypeParameters();
  604. else
  605. return (TypeVariable<Class<T>>[])new TypeVariable<?>[0];
  606. }
  607. /**
  608. * Returns the {@code Class} representing the superclass of the entity
  609. * (class, interface, primitive type or void) represented by this
  610. * {@code Class}. If this {@code Class} represents either the
  611. * {@code Object} class, an interface, a primitive type, or void, then
  612. * null is returned. If this object represents an array class then the
  613. * {@code Class} object representing the {@code Object} class is
  614. * returned.
  615. *
  616. * @return the superclass of the class represented by this object.
  617. */
  618. public native Class<? super T> getSuperclass();
  619. /**
  620. * Returns the {@code Type} representing the direct superclass of
  621. * the entity (class, interface, primitive type or void) represented by
  622. * this {@code Class}.
  623. *
  624. * <p>If the superclass is a parameterized type, the {@code Type}
  625. * object returned must accurately reflect the actual type
  626. * parameters used in the source code. The parameterized type
  627. * representing the superclass is created if it had not been
  628. * created before. See the declaration of {@link
  629. * java.lang.reflect.ParameterizedType ParameterizedType} for the
  630. * semantics of the creation process for parameterized types. If
  631. * this {@code Class} represents either the {@code Object}
  632. * class, an interface, a primitive type, or void, then null is
  633. * returned. If this object represents an array class then the
  634. * {@code Class} object representing the {@code Object} class is
  635. * returned.
  636. *
  637. * @throws java.lang.reflect.GenericSignatureFormatError if the generic
  638. * class signature does not conform to the format specified in
  639. * <cite>The Java&trade; Virtual Machine Specification</cite>
  640. * @throws TypeNotPresentException if the generic superclass
  641. * refers to a non-existent type declaration
  642. * @throws java.lang.reflect.MalformedParameterizedTypeException if the
  643. * generic superclass refers to a parameterized type that cannot be
  644. * instantiated for any reason
  645. * @return the superclass of the class represented by this object
  646. * @since 1.5
  647. */
  648. public Type getGenericSuperclass() {
  649. if (getGenericSignature() != null) {
  650. // Historical irregularity:
  651. // Generic signature marks interfaces with superclass = Object
  652. // but this API returns null for interfaces
  653. if (isInterface())
  654. return null;
  655. return getGenericInfo().getSuperclass();
  656. } else
  657. return getSuperclass();
  658. }
  659. /**
  660. * Gets the package for this class. The class loader of this class is used
  661. * to find the package. If the class was loaded by the bootstrap class
  662. * loader the set of packages loaded from CLASSPATH is searched to find the
  663. * package of the class. Null is returned if no package object was created
  664. * by the class loader of this class.
  665. *
  666. * <p> Packages have attributes for versions and specifications only if the
  667. * information was defined in the manifests that accompany the classes, and
  668. * if the class loader created the package instance with the attributes
  669. * from the manifest.
  670. *
  671. * @return the package of the class, or null if no package
  672. * information is available from the archive or codebase.
  673. */
  674. public Package getPackage() {
  675. return Package.getPackage(this);
  676. }
  677. /**
  678. * Determines the interfaces implemented by the class or interface
  679. * represented by this object.
  680. *
  681. * <p> If this object represents a class, the return value is an array
  682. * containing objects representing all interfaces implemented by the
  683. * class. The order of the interface objects in the array corresponds to
  684. * the order of the interface names in the {@code implements} clause
  685. * of the declaration of the class represented by this object. For
  686. * example, given the declaration:
  687. * <blockquote>
  688. * {@code class Shimmer implements FloorWax, DessertTopping { ... }}
  689. * </blockquote>
  690. * suppose the value of {@code s} is an instance of
  691. * {@code Shimmer}; the value of the expression:
  692. * <blockquote>
  693. * {@code s.getClass().getInterfaces()[0]}
  694. * </blockquote>
  695. * is the {@code Class} object that represents interface
  696. * {@code FloorWax}; and the value of:
  697. * <blockquote>
  698. * {@code s.getClass().getInterfaces()[1]}
  699. * </blockquote>
  700. * is the {@code Class} object that represents interface
  701. * {@code DessertTopping}.
  702. *
  703. * <p> If this object represents an interface, the array contains objects
  704. * representing all interfaces extended by the interface. The order of the
  705. * interface objects in the array corresponds to the order of the interface
  706. * names in the {@code extends} clause of the declaration of the
  707. * interface represented by this object.
  708. *
  709. * <p> If this object represents a class or interface that implements no
  710. * interfaces, the method returns an array of length 0.
  711. *
  712. * <p> If this object represents a primitive type or void, the method
  713. * returns an array of length 0.
  714. *
  715. * @return an array of interfaces implemented by this class.
  716. */
  717. public native Class<?>[] getInterfaces();
  718. /**
  719. * Returns the {@code Type}s representing the interfaces
  720. * directly implemented by the class or interface represented by
  721. * this object.
  722. *
  723. * <p>If a superinterface is a parameterized type, the
  724. * {@code Type} object returned for it must accurately reflect
  725. * the actual type parameters used in the source code. The
  726. * parameterized type representing each superinterface is created
  727. * if it had not been created before. See the declaration of
  728. * {@link java.lang.reflect.ParameterizedType ParameterizedType}
  729. * for the semantics of the creation process for parameterized
  730. * types.
  731. *
  732. * <p> If this object represents a class, the return value is an
  733. * array containing objects representing all interfaces
  734. * implemented by the class. The order of the interface objects in
  735. * the array corresponds to the order of the interface names in
  736. * the {@code implements} clause of the declaration of the class
  737. * represented by this object. In the case of an array class, the
  738. * interfaces {@code Cloneable} and {@code Serializable} are
  739. * returned in that order.
  740. *
  741. * <p>If this object represents an interface, the array contains
  742. * objects representing all interfaces directly extended by the
  743. * interface. The order of the interface objects in the array
  744. * corresponds to the order of the interface names in the
  745. * {@code extends} clause of the declaration of the interface
  746. * represented by this object.
  747. *
  748. * <p>If this object represents a class or interface that
  749. * implements no interfaces, the method returns an array of length
  750. * 0.
  751. *
  752. * <p>If this object represents a primitive type or void, the
  753. * method returns an array of length 0.
  754. *
  755. * @throws java.lang.reflect.GenericSignatureFormatError
  756. * if the generic class signature does not conform to the format
  757. * specified in
  758. * <cite>The Java&trade; Virtual Machine Specification</cite>
  759. * @throws TypeNotPresentException if any of the generic
  760. * superinterfaces refers to a non-existent type declaration
  761. * @throws java.lang.reflect.MalformedParameterizedTypeException
  762. * if any of the generic superinterfaces refer to a parameterized
  763. * type that cannot be instantiated for any reason
  764. * @return an array of interfaces implemented by this class
  765. * @since 1.5
  766. */
  767. public Type[] getGenericInterfaces() {
  768. if (getGenericSignature() != null)
  769. return getGenericInfo().getSuperInterfaces();
  770. else
  771. return getInterfaces();
  772. }
  773. /**
  774. * Returns the {@code Class} representing the component type of an
  775. * array. If this class does not represent an array class this method
  776. * returns null.
  777. *
  778. * @return the {@code Class} representing the component type of this
  779. * class if this class is an array
  780. * @see java.lang.reflect.Array
  781. * @since JDK1.1
  782. */
  783. public native Class<?> getComponentType();
  784. /**
  785. * Returns the Java language modifiers for this class or interface, encoded
  786. * in an integer. The modifiers consist of the Java Virtual Machine's
  787. * constants for {@code public}, {@code protected},
  788. * {@code private}, {@code final}, {@code static},
  789. * {@code abstract} and {@code interface}; they should be decoded
  790. * using the methods of class {@code Modifier}.
  791. *
  792. * <p> If the underlying class is an array class, then its
  793. * {@code public}, {@code private} and {@code protected}
  794. * modifiers are the same as those of its component type. If this
  795. * {@code Class} represents a primitive type or void, its
  796. * {@code public} modifier is always {@code true}, and its
  797. * {@code protected} and {@code private} modifiers are always
  798. * {@code false}. If this object represents an array class, a
  799. * primitive type or void, then its {@code final} modifier is always
  800. * {@code true} and its interface modifier is always
  801. * {@code false}. The values of its other modifiers are not determined
  802. * by this specification.
  803. *
  804. * <p> The modifier encodings are defined in <em>The Java Virtual Machine
  805. * Specification</em>, table 4.1.
  806. *
  807. * @return the {@code int} representing the modifiers for this class
  808. * @see java.lang.reflect.Modifier
  809. * @since JDK1.1
  810. */
  811. public native int getModifiers();
  812. /**
  813. * Gets the signers of this class.
  814. *
  815. * @return the signers of this class, or null if there are no signers. In
  816. * particular, this method returns null if this object represents
  817. * a primitive type or void.
  818. * @since JDK1.1
  819. */
  820. public native Object[] getSigners();
  821. /**
  822. * Set the signers of this class.
  823. */
  824. native void setSigners(Object[] signers);
  825. /**
  826. * If this {@code Class} object represents a local or anonymous
  827. * class within a method, returns a {@link
  828. * java.lang.reflect.Method Method} object representing the
  829. * immediately enclosing method of the underlying class. Returns
  830. * {@code null} otherwise.
  831. *
  832. * In particular, this method returns {@code null} if the underlying
  833. * class is a local or anonymous class immediately enclosed by a type
  834. * declaration, instance initializer or static initializer.
  835. *
  836. * @return the immediately enclosing method of the underlying class, if
  837. * that class is a local or anonymous class; otherwise {@code null}.
  838. * @since 1.5
  839. */
  840. public Method getEnclosingMethod() {
  841. EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
  842. if (enclosingInfo == null)
  843. return null;
  844. else {
  845. if (!enclosingInfo.isMethod())
  846. return null;
  847. MethodRepository typeInfo = MethodRepository.make(enclosingInfo.getDescriptor(),
  848. getFactory());
  849. Class<?> returnType = toClass(typeInfo.getReturnType());
  850. Type [] parameterTypes = typeInfo.getParameterTypes();
  851. Class<?>[] parameterClasses = new Class<?>[parameterTypes.length];
  852. // Convert Types to Classes; returned types *should*
  853. // be class objects since the methodDescriptor's used
  854. // don't have generics information
  855. for(int i = 0; i < parameterClasses.length; i++)
  856. parameterClasses[i] = toClass(parameterTypes[i]);
  857. /*
  858. * Loop over all declared methods; match method name,
  859. * number of and type of parameters, *and* return
  860. * type. Matching return type is also necessary
  861. * because of covariant returns, etc.
  862. */
  863. for(Method m: enclosingInfo.getEnclosingClass().getDeclaredMethods()) {
  864. if (m.getName().equals(enclosingInfo.getName()) ) {
  865. Class<?>[] candidateParamClasses = m.getParameterTypes();
  866. if (candidateParamClasses.length == parameterClasses.length) {
  867. boolean matches = true;
  868. for(int i = 0; i < candidateParamClasses.length; i++) {
  869. if (!candidateParamClasses[i].equals(parameterClasses[i])) {
  870. matches = false;
  871. break;
  872. }
  873. }
  874. if (matches) { // finally, check return type
  875. if (m.getReturnType().equals(returnType) )
  876. return m;
  877. }
  878. }
  879. }
  880. }
  881. throw new InternalError("Enclosing method not found");
  882. }
  883. }
  884. private native Object[] getEnclosingMethod0();
  885. private EnclosingMethodInfo getEnclosingMethodInfo() {
  886. Object[] enclosingInfo = getEnclosingMethod0();
  887. if (enclosingInfo == null)
  888. return null;
  889. else {
  890. return new EnclosingMethodInfo(enclosingInfo);
  891. }
  892. }
  893. private final static class EnclosingMethodInfo {
  894. private Class<?> enclosingClass;
  895. private String name;
  896. private String descriptor;
  897. private EnclosingMethodInfo(Object[] enclosingInfo) {
  898. if (enclosingInfo.length != 3)
  899. throw new InternalError("Malformed enclosing method information");
  900. try {
  901. // The array is expected to have three elements:
  902. // the immediately enclosing class
  903. enclosingClass = (Class<?>) enclosingInfo[0];
  904. assert(enclosingClass != null);
  905. // the immediately enclosing method or constructor's
  906. // name (can be null).
  907. name = (String) enclosingInfo[1];
  908. // the immediately enclosing method or constructor's
  909. // descriptor (null iff name is).
  910. descriptor = (String) enclosingInfo[2];
  911. assert((name != null && descriptor != null) || name == descriptor);
  912. } catch (ClassCastException cce) {
  913. throw new InternalError("Invalid type in enclosing method information", cce);
  914. }
  915. }
  916. boolean isPartial() {
  917. return enclosingClass == null || name == null || descriptor == null;
  918. }
  919. boolean isConstructor() { return !isPartial() && "<init>".equals(name); }
  920. boolean isMethod() { return !isPartial() && !isConstructor() && !"<clinit>".equals(name); }
  921. Class<?> getEnclosingClass() { return enclosingClass; }
  922. String getName() { return name; }
  923. String getDescriptor() { return descriptor; }
  924. }
  925. private static Class<?> toClass(Type o) {
  926. if (o instanceof GenericArrayType)
  927. return Array.newInstance(toClass(((GenericArrayType)o).getGenericComponentType()),
  928. 0)
  929. .getClass();
  930. return (Class<?>)o;
  931. }
  932. /**
  933. * If this {@code Class} object represents a local or anonymous
  934. * class within a constructor, returns a {@link
  935. * java.lang.reflect.Constructor Constructor} object representing
  936. * the immediately enclosing constructor of the underlying
  937. * class. Returns {@code null} otherwise. In particular, this
  938. * method returns {@code null} if the underlying class is a local
  939. * or anonymous class immediately enclosed by a type declaration,
  940. * instance initializer or static initializer.
  941. *
  942. * @return the immediately enclosing constructor of the underlying class, if
  943. * that class is a local or anonymous class; otherwise {@code null}.
  944. * @since 1.5
  945. */
  946. public Constructor<?> getEnclosingConstructor() {
  947. EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
  948. if (enclosingInfo == null)
  949. return null;
  950. else {
  951. if (!enclosingInfo.isConstructor())
  952. return null;
  953. ConstructorRepository typeInfo = ConstructorRepository.make(enclosingInfo.getDescriptor(),
  954. getFactory());
  955. Type [] parameterTypes = typeInfo.getParameterTypes();
  956. Class<?>[] parameterClasses = new Class<?>[parameterTypes.length];
  957. // Convert Types to Classes; returned types *should*
  958. // be class objects since the methodDescriptor's used
  959. // don't have generics information
  960. for(int i = 0; i < parameterClasses.length; i++)
  961. parameterClasses[i] = toClass(parameterTypes[i]);
  962. /*
  963. * Loop over all declared constructors; match number
  964. * of and type of parameters.
  965. */
  966. for(Constructor<?> c: enclosingInfo.getEnclosingClass().getDeclaredConstructors()) {
  967. Class<?>[] candidateParamClasses = c.getParameterTypes();
  968. if (candidateParamClasses.length == parameterClasses.length) {
  969. boolean matches = true;
  970. for(int i = 0; i < candidateParamClasses.length; i++) {
  971. if (!candidateParamClasses[i].equals(parameterClasses[i])) {
  972. matches = false;
  973. break;
  974. }
  975. }
  976. if (matches)
  977. return c;
  978. }
  979. }
  980. throw new InternalError("Enclosing constructor not found");
  981. }
  982. }
  983. /**
  984. * If the class or interface represented by this {@code Class} object
  985. * is a member of another class, returns the {@code Class} object
  986. * representing the class in which it was declared. This method returns
  987. * null if this class or interface is not a member of any other class. If
  988. * this {@code Class} object represents an array class, a primitive
  989. * type, or void,then this method returns null.
  990. *
  991. * @return the declaring class for this class
  992. * @since JDK1.1
  993. */
  994. public native Class<?> getDeclaringClass();
  995. /**
  996. * Returns the immediately enclosing class of the underlying
  997. * class. If the underlying class is a top level class this
  998. * method returns {@code null}.
  999. * @return the immediately enclosing class of the underlying class
  1000. * @since 1.5
  1001. */
  1002. public Class<?> getEnclosingClass() {
  1003. // There are five kinds of classes (or interfaces):
  1004. // a) Top level classes
  1005. // b) Nested classes (static member classes)
  1006. // c) Inner classes (non-static member classes)
  1007. // d) Local classes (named classes declared within a method)
  1008. // e) Anonymous classes
  1009. // JVM Spec 4.8.6: A class must have an EnclosingMethod
  1010. // attribute if and only if it is a local class or an
  1011. // anonymous class.
  1012. EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
  1013. if (enclosingInfo == null) {
  1014. // This is a top level or a nested class or an inner class (a, b, or c)
  1015. return getDeclaringClass();
  1016. } else {
  1017. Class<?> enclosingClass = enclosingInfo.getEnclosingClass();
  1018. // This is a local class or an anonymous class (d or e)
  1019. if (enclosingClass == this || enclosingClass == null)
  1020. throw new InternalError("Malformed enclosing method information");
  1021. else
  1022. return enclosingClass;
  1023. }
  1024. }
  1025. /**
  1026. * Returns the simple name of the underlying class as given in the
  1027. * source code. Returns an empty string if the underlying class is
  1028. * anonymous.
  1029. *
  1030. * <p>The simple name of an array is the simple name of the
  1031. * component type with "[]" appended. In particular the simple
  1032. * name of an array whose component type is anonymous is "[]".
  1033. *
  1034. * @return the simple name of the underlying class
  1035. * @since 1.5
  1036. */
  1037. public String getSimpleName() {
  1038. if (isArray())
  1039. return getComponentType().getSimpleName()+"[]";
  1040. String simpleName = getSimpleBinaryName();
  1041. if (simpleName == null) { // top level class
  1042. simpleName = getName();
  1043. return simpleName.substring(simpleName.lastIndexOf(".")+1); // strip the package name
  1044. }
  1045. // According to JLS3 "Binary Compatibility" (13.1) the binary
  1046. // name of non-package classes (not top level) is the binary
  1047. // name of the immediately enclosing class followed by a '$' followed by:
  1048. // (for nested and inner classes): the simple name.
  1049. // (for local classes): 1 or more digits followed by the simple name.
  1050. // (for anonymous classes): 1 or more digits.
  1051. // Since getSimpleBinaryName() will strip the binary name of
  1052. // the immediatly enclosing class, we are now looking at a
  1053. // string that matches the regular expression "\$[0-9]*"
  1054. // followed by a simple name (considering the simple of an
  1055. // anonymous class to be the empty string).
  1056. // Remove leading "\$[0-9]*" from the name
  1057. int length = simpleName.length();
  1058. if (length < 1 || simpleName.charAt(0) != '$')
  1059. throw new InternalError("Malformed class name");
  1060. int index = 1;
  1061. while (index < length && isAsciiDigit(simpleName.charAt(index)))
  1062. index++;
  1063. // Eventually, this is the empty string iff this is an anonymous class
  1064. return simpleName.substring(index);
  1065. }
  1066. /**
  1067. * Character.isDigit answers {@code true} to some non-ascii
  1068. * digits. This one does not.
  1069. */
  1070. private static boolean isAsciiDigit(char c) {
  1071. return '0' <= c && c <= '9';
  1072. }
  1073. /**
  1074. * Returns the canonical name of the underlying class as
  1075. * defined by the Java Language Specification. Returns null if
  1076. * the underlying class does not have a canonical name (i.e., if
  1077. * it is a local or anonymous class or an array whose component
  1078. * type does not have a canonical name).
  1079. * @return the canonical name of the underlying class if it exists, and
  1080. * {@code null} otherwise.
  1081. * @since 1.5
  1082. */
  1083. public String getCanonicalName() {
  1084. if (isArray()) {
  1085. String canonicalName = getComponentType().getCanonicalName();
  1086. if (canonicalName != null)
  1087. return canonicalName + "[]";
  1088. else
  1089. return null;
  1090. }
  1091. if (isLocalOrAnonymousClass())
  1092. return null;
  1093. Class<?> enclosingClass = getEnclosingClass();
  1094. if (enclosingClass == null) { // top level class
  1095. return getName();
  1096. } else {
  1097. String enclosingName = enclosingClass.getCanonicalName();
  1098. if (enclosingName == null)
  1099. return null;
  1100. return enclosingName + "." + getSimpleName();
  1101. }
  1102. }
  1103. /**
  1104. * Returns {@code true} if and only if the underlying class
  1105. * is an anonymous class.
  1106. *
  1107. * @return {@code true} if and only if this class is an anonymous class.
  1108. * @since 1.5
  1109. */
  1110. public boolean isAnonymousClass() {
  1111. return "".equals(getSimpleName());
  1112. }
  1113. /**
  1114. * Returns {@code true} if and only if the underlying class
  1115. * is a local class.
  1116. *
  1117. * @return {@code true} if and only if this class is a local class.
  1118. * @since 1.5
  1119. */
  1120. public boolean isLocalClass() {
  1121. return isLocalOrAnonymousClass() && !isAnonymousClass();
  1122. }
  1123. /**
  1124. * Returns {@code true} if and only if the underlying class
  1125. * is a member class.
  1126. *
  1127. * @return {@code true} if and only if this class is a member class.
  1128. * @since 1.5
  1129. */
  1130. public boolean isMemberClass() {
  1131. return getSimpleBinaryName() != null && !isLocalOrAnonymousClass();
  1132. }
  1133. /**
  1134. * Returns the "simple binary name" of the underlying class, i.e.,
  1135. * the binary name without the leading enclosing class name.
  1136. * Returns {@code null} if the underlying class is a top level
  1137. * class.
  1138. */
  1139. private String getSimpleBinaryName() {
  1140. Class<?> enclosingClass = getEnclosingClass();
  1141. if (enclosingClass == null) // top level class
  1142. return null;
  1143. // Otherwise, strip the enclosing class' name
  1144. try {
  1145. return getName().substring(enclosingClass.getName().length());
  1146. } catch (IndexOutOfBoundsException ex) {
  1147. throw new InternalError("Malformed class name", ex);
  1148. }
  1149. }
  1150. /**
  1151. * Returns {@code true} if this is a local class or an anonymous
  1152. * class. Returns {@code false} otherwise.
  1153. */
  1154. private boolean isLocalOrAnonymousClass() {
  1155. // JVM Spec 4.8.6: A class must have an EnclosingMethod
  1156. // attribute if and only if it is a local class or an
  1157. // anonymous class.
  1158. return getEnclosingMethodInfo() != null;
  1159. }
  1160. /**
  1161. * Returns an array containing {@code Class} objects representing all
  1162. * the public classes and interfaces that are members of the class
  1163. * represented by this {@code Class} object. This includes public
  1164. * class and interface members inherited from superclasses and public class
  1165. * and interface members declared by the class. This method returns an
  1166. * array of length 0 if this {@code Class} object has no public member
  1167. * classes or interfaces. This method also returns an array of length 0 if
  1168. * this {@code Class} object represents a primitive type, an array
  1169. * class, or void.
  1170. *
  1171. * @return the array of {@code Class} objects representing the public
  1172. * members of this class
  1173. * @exception SecurityException
  1174. * If a security manager, <i>s</i>, is present and any of the
  1175. * following conditions is met:
  1176. *
  1177. * <ul>
  1178. *
  1179. * <li> invocation of
  1180. * {@link SecurityManager#checkMemberAccess
  1181. * s.checkMemberAccess(this, Member.PUBLIC)} method
  1182. * denies access to the classes within this class
  1183. *
  1184. * <li> the caller's class loader is not the same as or an
  1185. * ancestor of the class loader for the current class and
  1186. * invocation of {@link SecurityManager#checkPackageAccess
  1187. * s.checkPackageAccess()} denies access to the package
  1188. * of this class
  1189. *
  1190. * </ul>
  1191. *
  1192. * @since JDK1.1
  1193. */
  1194. public Class<?>[] getClasses() {
  1195. // be very careful not to change the stack depth of this
  1196. // checkMemberAccess call for security reasons
  1197. // see java.lang.SecurityManager.checkMemberAccess
  1198. checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader());
  1199. // Privileged so this implementation can look at DECLARED classes,
  1200. // something the caller might not have privilege to do. The code here
  1201. // is allowed to look at DECLARED classes because (1) it does not hand
  1202. // out anything other than public members and (2) public member access
  1203. // has already been ok'd by the SecurityManager.
  1204. return java.security.AccessController.doPrivileged(
  1205. new java.security.PrivilegedAction<Class<?>[]>() {
  1206. public Class[] run() {
  1207. List<Class<?>> list = new ArrayList<>();
  1208. Class<?> currentClass = Class.this;
  1209. while (currentClass != null) {
  1210. Class<?>[] members = currentClass.getDeclaredClasses();
  1211. for (int i = 0; i < members.length; i++) {
  1212. if (Modifier.isPublic(members[i].getModifiers())) {
  1213. list.add(members[i]);
  1214. }
  1215. }
  1216. currentClass = currentClass.getSuperclass();
  1217. }
  1218. return list.toArray(new Class[0]);
  1219. }
  1220. });
  1221. }
  1222. /**
  1223. * Returns an array containing {@code Field} objects reflecting all
  1224. * the accessible public fields of the class or interface represented by
  1225. * this {@code Class} object. The elements in the array returned are
  1226. * not sorted and are not in any particular order. This method returns an
  1227. * array of length 0 if the class or interface has no accessible public
  1228. * fields, or if it represents an array class, a primitive type, or void.
  1229. *
  1230. * <p> Specifically, if this {@code Class} object represents a class,
  1231. * this method returns the public fields of this class and of all its
  1232. * superclasses. If this {@code Class} object represents an
  1233. * interface, this method returns the fields of this interface and of all
  1234. * its superinterfaces.
  1235. *
  1236. * <p> The implicit length field for array class is not reflected by this
  1237. * method. User code should use the methods of class {@code Array} to
  1238. * manipulate arrays.
  1239. *
  1240. * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3.
  1241. *
  1242. * @return the array of {@code Field} objects representing the
  1243. * public fields
  1244. * @exception SecurityException
  1245. * If a security manager, <i>s</i>, is present and any of the
  1246. * following conditions is met:
  1247. *
  1248. * <ul>
  1249. *
  1250. * <li> invocation of
  1251. * {@link SecurityManager#checkMemberAccess
  1252. * s.checkMemberAccess(this, Member.PUBLIC)} denies
  1253. * access to the fields within this class
  1254. *
  1255. * <li> the caller's class loader is not the same as or an
  1256. * ancestor of the class loader for the current class and
  1257. * invocation of {@link SecurityManager#checkPackageAccess
  1258. * s.checkPackageAccess()} denies access to the package
  1259. * of this class
  1260. *
  1261. * </ul>
  1262. *
  1263. * @since JDK1.1
  1264. */
  1265. public Field[] getFields() throws SecurityException {
  1266. // be very careful not to change the stack depth of this
  1267. // checkMemberAccess call for security reasons
  1268. // see java.lang.SecurityManager.checkMemberAccess
  1269. checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader());
  1270. return copyFields(privateGetPublicFields(null));
  1271. }
  1272. /**
  1273. * Returns an array containing {@code Method} objects reflecting all
  1274. * the public <em>member</em> methods of the class or interface represented
  1275. * by this {@code Class} object, including those declared by the class
  1276. * or interface and those inherited from superclasses and
  1277. * superinterfaces. Array classes return all the (public) member methods
  1278. * inherited from the {@code Object} class. The elements in the array
  1279. * returned are not sorted and are not in any particular order. This
  1280. * method returns an array of length 0 if this {@code Class} object
  1281. * represents a class or interface that has no public member methods, or if
  1282. * this {@code Class} object represents a primitive type or void.
  1283. *
  1284. * <p> The class initialization method {@code <clinit>} is not
  1285. * included in the returned array. If the class declares multiple public
  1286. * member methods with the same parameter types, they are all included in
  1287. * the returned array.
  1288. *
  1289. * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.4.
  1290. *
  1291. * @return the array of {@code Method} objects representing the
  1292. * public methods of this class
  1293. * @exception SecurityException
  1294. * If a security manager, <i>s</i>, is present and any of the
  1295. * following conditions is met:
  1296. *
  1297. * <ul>
  1298. *
  1299. * <li> invocation of
  1300. * {@link SecurityManager#checkMemberAccess
  1301. * s.checkMemberAccess(this, Member.PUBLIC)} denies
  1302. * access to the methods within this class
  1303. *
  1304. * <li> the caller's class loader is not the same as or an
  1305. * ancestor of the class loader for the current class and
  1306. * invocation of {@link SecurityManager#checkPackageAccess
  1307. * s.checkPackageAccess()} denies access to the package
  1308. * of this class
  1309. *
  1310. * </ul>
  1311. *
  1312. * @since JDK1.1
  1313. */
  1314. public Method[] getMethods() throws SecurityException {
  1315. // be very careful not to change the stack depth of this
  1316. // checkMemberAccess call for security reasons
  1317. // see java.lang.SecurityManager.checkMemberAccess
  1318. checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader());
  1319. return copyMethods(privateGetPublicMethods());
  1320. }
  1321. /**
  1322. * Returns an array containing {@code Constructor} objects reflecting
  1323. * all the public constructors of the class represented by this
  1324. * {@code Class} object. An array of length 0 is returned if the
  1325. * class has no public constructors, or if the class is an array class, or
  1326. * if the class reflects a primitive type or void.
  1327. *
  1328. * Note that while this method returns an array of {@code
  1329. * Constructor<T>} objects (that is an array of constructors from
  1330. * this class), the return type of this method is {@code
  1331. * Constructor<?>[]} and <em>not</em> {@code Constructor<T>[]} as
  1332. * might be expected. This less informative return type is
  1333. * necessary since after being returned from this method, the
  1334. * array could be modified to hold {@code Constructor} objects for
  1335. * different classes, which would violate the type guarantees of
  1336. * {@code Constructor<T>[]}.
  1337. *
  1338. * @return the array of {@code Constructor} objects representing the
  1339. * public constructors of this class
  1340. * @exception SecurityException
  1341. * If a security manager, <i>s</i>, is present and any of the
  1342. * following conditions is met:
  1343. *
  1344. * <ul>
  1345. *
  1346. * <li> invocation of
  1347. * {@link SecurityManager#checkMemberAccess
  1348. * s.checkMemberAccess(this, Member.PUBLIC)} denies
  1349. * access to the constructors within this class
  1350. *
  1351. * <li> the caller's class loader is not the same as or an
  1352. * ancestor of the class loader for the current class and
  1353. * invocation of {@link SecurityManager#checkPackageAccess
  1354. * s.checkPackageAccess()} denies access to the package
  1355. * of this class
  1356. *
  1357. * </ul>
  1358. *
  1359. * @since JDK1.1
  1360. */
  1361. public Constructor<?>[] getConstructors() throws SecurityException {
  1362. // be very careful not to change the stack depth of this
  1363. // checkMemberAccess call for security reasons
  1364. // see java.lang.SecurityManager.checkMemberAccess
  1365. checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader());
  1366. return copyConstructors(privateGetDeclaredConstructors(true));
  1367. }
  1368. /**
  1369. * Returns a {@code Field} object that reflects the specified public
  1370. * member field of the class or interface represented by this
  1371. * {@code Class} object. The {@code name} parameter is a
  1372. * {@code String} specifying the simple name of the desired field.
  1373. *
  1374. * <p> The field to be reflected is determined by the algorithm that
  1375. * follows. Let C be the class represented by this object:
  1376. * <OL>
  1377. * <LI> If C declares a public field with the name specified, that is the
  1378. * field to be reflected.</LI>
  1379. * <LI> If no field was found in step 1 above, this algorithm is applied
  1380. * recursively to each direct superinterface of C. The direct
  1381. * superinterfaces are searched in the order they were declared.</LI>
  1382. * <LI> If no field was found in steps 1 and 2 above, and C has a
  1383. * superclass S, then this algorithm is invoked recursively upon S.
  1384. * If C has no superclass, then a {@code NoSuchFieldException}
  1385. * is thrown.</LI>
  1386. * </OL>
  1387. *
  1388. * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3.
  1389. *
  1390. * @param name the field name
  1391. * @return the {@code Field} object of this class specified by
  1392. * {@code name}
  1393. * @exception NoSuchFieldException if a field with the specified name is
  1394. * not found.
  1395. * @exception NullPointerException if {@code name} is {@code null}
  1396. * @exception SecurityException
  1397. * If a security manager, <i>s</i>, is present and any of the
  1398. * following conditions is met:
  1399. *
  1400. * <ul>
  1401. *
  1402. * <li> invocation of
  1403. * {@link SecurityManager#checkMemberAccess
  1404. * s.checkMemberAccess(this, Member.PUBLIC)} denies
  1405. * access to the field
  1406. *
  1407. * <li> the caller's class loader is not the same as or an
  1408. * ancestor of the class loader for the current class and
  1409. * invocation of {@link SecurityManager#checkPackageAccess
  1410. * s.checkPackageAccess()} denies access to the package
  1411. * of this class
  1412. *
  1413. * </ul>
  1414. *
  1415. * @since JDK1.1
  1416. */
  1417. public Field getField(String name)
  1418. throws NoSuchFieldException, SecurityException {
  1419. // be very careful not to change the stack depth of this
  1420. // checkMemberAccess call for security reasons
  1421. // see java.lang.SecurityManager.checkMemberAccess
  1422. checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader());
  1423. Field field = getField0(name);
  1424. if (field == null) {
  1425. throw new NoSuchFieldException(name);
  1426. }
  1427. return field;
  1428. }
  1429. /**
  1430. * Returns a {@code Method} object that reflects the specified public
  1431. * member method of the class or interface represented by this
  1432. * {@code Class} object. The {@code name} parameter is a
  1433. * {@code String} specifying the simple name of the desired method. The
  1434. * {@code parameterTypes} parameter is an array of {@code Class}
  1435. * objects that identify the method's formal parameter types, in declared
  1436. * order. If {@code parameterTypes} is {@code null}, it is
  1437. * treated as if it were an empty array.
  1438. *
  1439. * <p> If the {@code name} is "{@code <init>};"or "{@code <clinit>}" a
  1440. * {@code NoSuchMethodException} is raised. Otherwise, the method to
  1441. * be reflected is determined by the algorithm that follows. Let C be the
  1442. * class represented by this object:
  1443. * <OL>
  1444. * <LI> C is searched for any <I>matching methods</I>. If no matching
  1445. * method is found, the algorithm of step 1 is invoked recursively on
  1446. * the superclass of C.</LI>
  1447. * <LI> If no method was found in step 1 above, the superinterfaces of C
  1448. * are searched for a matching method. If any such method is found, it
  1449. * is reflected.</LI>
  1450. * </OL>
  1451. *
  1452. * To find a matching method in a class C:&nbsp; If C declares exactly one
  1453. * public method with the specified name and exactly the same formal
  1454. * parameter types, that is the method reflected. If more than one such
  1455. * method is found in C, and one of these methods has a return type that is
  1456. * more specific than any of the others, that method is reflected;
  1457. * otherwise one of the methods is chosen arbitrarily.
  1458. *
  1459. * <p>Note that there may be more than one matching method in a
  1460. * class because while the Java language forbids a class to
  1461. * declare multiple methods with the same signature but different
  1462. * return types, the Java virtual machine does not. This
  1463. * increased flexibility in the virtual machine can be used to
  1464. * implement various language features. For example, covariant
  1465. * returns can be implemented with {@linkplain
  1466. * java.lang.reflect.Method#isBridge bridge methods}; the bridge
  1467. * method and the method being overridden would have the same
  1468. * signature but different return types.
  1469. *
  1470. * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.4.
  1471. *
  1472. * @param name the name of the method
  1473. * @param parameterTypes the list of parameters
  1474. * @return the {@code Method} object that matches the specified
  1475. * {@code name} and {@code parameterTypes}
  1476. * @exception NoSuchMethodException if a matching method is not found
  1477. * or if the name is "&lt;init&gt;"or "&lt;clinit&gt;".
  1478. * @exception NullPointerException if {@code name} is {@code null}
  1479. * @exception SecurityException
  1480. * If a security manager, <i>s</i>, is present and any of the
  1481. * following conditions is met:
  1482. *
  1483. * <ul>
  1484. *
  1485. * <li> invocation of
  1486. * {@link SecurityManager#checkMemberAccess
  1487. * s.checkMemberAccess(this, Member.PUBLIC)} denies
  1488. * access to the method
  1489. *
  1490. * <li> the caller's class loader is not the same as or an
  1491. * ancestor of the class loader for the current class and
  1492. * invocation of {@link SecurityManager#checkPackageAccess
  1493. * s.checkPackageAccess()} denies access to the package
  1494. * of this class
  1495. *
  1496. * </ul>
  1497. *
  1498. * @since JDK1.1
  1499. */
  1500. public Method getMethod(String name, Class<?>... parameterTypes)
  1501. throws NoSuchMethodException, SecurityException {
  1502. // be very careful not to change the stack depth of this
  1503. // checkMemberAccess call for security reasons
  1504. // see java.lang.SecurityManager.checkMemberAccess
  1505. checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader());
  1506. Method method = getMethod0(name, parameterTypes);
  1507. if (method == null) {
  1508. throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes));
  1509. }
  1510. return method;
  1511. }
  1512. /**
  1513. * Returns a {@code Constructor} object that reflects the specified
  1514. * public constructor of the class represented by this {@code Class}
  1515. * object. The {@code parameterTypes} parameter is an array of
  1516. * {@code Class} objects that identify the constructor's formal
  1517. * parameter types, in declared order.
  1518. *
  1519. * If this {@code Class} object represents an inner class
  1520. * declared in a non-static context, the formal parameter types
  1521. * include the explicit enclosing instance as the first parameter.
  1522. *
  1523. * <p> The constructor to reflect is the public constructor of the class
  1524. * represented by this {@code Class} object whose formal parameter
  1525. * types match those specified by {@code parameterTypes}.
  1526. *
  1527. * @param parameterTypes the parameter array
  1528. * @return the {@code Constructor} object of the public constructor that
  1529. * matches the specified {@code parameterTypes}
  1530. * @exception NoSuchMethodException if a matching method is not found.
  1531. * @exception SecurityException
  1532. * If a security manager, <i>s</i>, is present and any of the
  1533. * following conditions is met:
  1534. *
  1535. * <ul>
  1536. *
  1537. * <li> invocation of
  1538. * {@link SecurityManager#checkMemberAccess
  1539. * s.checkMemberAccess(this, Member.PUBLIC)} denies
  1540. * access to the constructor
  1541. *
  1542. * <li> the caller's class loader is not the same as or an
  1543. * ancestor of the class loader for the current class and
  1544. * invocation of {@link SecurityManager#checkPackageAccess
  1545. * s.checkPackageAccess()} denies access to the package
  1546. * of this class
  1547. *
  1548. * </ul>
  1549. *
  1550. * @since JDK1.1
  1551. */
  1552. public Constructor<T> getConstructor(Class<?>... parameterTypes)
  1553. throws NoSuchMethodException, SecurityException {
  1554. // be very careful not to change the stack depth of this
  1555. // checkMemberAccess call for security reasons
  1556. // see java.lang.SecurityManager.checkMemberAccess
  1557. checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader());
  1558. return getConstructor0(parameterTypes, Member.PUBLIC);
  1559. }
  1560. /**
  1561. * Returns an array of {@code Class} objects reflecting all the
  1562. * classes and interfaces declared as members of the class represented by
  1563. * this {@code Class} object. This includes public, protected, default
  1564. * (package) access, and private classes and interfaces declared by the
  1565. * class, but excludes inherited classes and interfaces. This method
  1566. * returns an array of length 0 if the class declares no classes or
  1567. * interfaces as members, or if this {@code Class} object represents a
  1568. * primitive type, an array class, or void.
  1569. *
  1570. * @return the array of {@code Class} objects representing all the
  1571. * declared members of this class
  1572. * @exception SecurityException
  1573. * If a security manager, <i>s</i>, is present and any of the
  1574. * following conditions is met:
  1575. *
  1576. * <ul>
  1577. *
  1578. * <li> invocation of
  1579. * {@link SecurityManager#checkMemberAccess
  1580. * s.checkMemberAccess(this, Member.DECLARED)} denies
  1581. * access to the declared classes within this class
  1582. *
  1583. * <li> the caller's class loader is not the same as or an
  1584. * ancestor of the class loader for the current class and
  1585. * invocation of {@link SecurityManager#checkPackageAccess
  1586. * s.checkPackageAccess()} denies access to the package
  1587. * of this class
  1588. *
  1589. * </ul>
  1590. *
  1591. * @since JDK1.1
  1592. */
  1593. public Class<?>[] getDeclaredClasses() throws SecurityException {
  1594. // be very careful not to change the stack depth of this
  1595. // checkMemberAccess call for security reasons
  1596. // see java.lang.SecurityManager.checkMemberAccess
  1597. checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader());
  1598. return getDeclaredClasses0();
  1599. }
  1600. /**
  1601. * Returns an array of {@code Field} objects reflecting all the fields
  1602. * declared by the class or interface represented by this
  1603. * {@code Class} object. This includes public, protected, default
  1604. * (package) access, and private fields, but excludes inherited fields.
  1605. * The elements in the array returned are not sorted and are not in any
  1606. * particular order. This method returns an array of length 0 if the class
  1607. * or interface declares no fields, or if this {@code Class} object
  1608. * represents a primitive type, an array class, or void.
  1609. *
  1610. * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3.
  1611. *
  1612. * @return the array of {@code Field} objects representing all the
  1613. * declared fields of this class
  1614. * @exception SecurityException
  1615. * If a security manager, <i>s</i>, is present and any of the
  1616. * following conditions is met:
  1617. *
  1618. * <ul>
  1619. *
  1620. * <li> invocation of
  1621. * {@link SecurityManager#checkMemberAccess
  1622. * s.checkMemberAccess(this, Member.DECLARED)} denies
  1623. * access to the declared fields within this class
  1624. *
  1625. * <li> the caller's class loader is not the same as or an
  1626. * ancestor of the class loader for the current class and
  1627. * invocation of {@link SecurityManager#checkPackageAccess
  1628. * s.checkPackageAccess()} denies access to the package
  1629. * of this class
  1630. *
  1631. * </ul>
  1632. *
  1633. * @since JDK1.1
  1634. */
  1635. public Field[] getDeclaredFields() throws SecurityException {
  1636. // be very careful not to change the stack depth of this
  1637. // checkMemberAccess call for security reasons
  1638. // see java.lang.SecurityManager.checkMemberAccess
  1639. checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader());
  1640. return copyFields(privateGetDeclaredFields(false));
  1641. }
  1642. /**
  1643. * Returns an array of {@code Method} objects reflecting all the
  1644. * methods declared by the class or interface represented by this
  1645. * {@code Class} object. This includes public, protected, default
  1646. * (package) access, and private methods, but excludes inherited methods.
  1647. * The elements in the array returned are not sorted and are not in any
  1648. * particular order. This method returns an array of length 0 if the class
  1649. * or interface declares no methods, or if this {@code Class} object
  1650. * represents a primitive type, an array class, or void. The class
  1651. * initialization method {@code <clinit>} is not included in the
  1652. * returned array. If the class declares multiple public member methods
  1653. * with the same parameter types, they are all included in the returned
  1654. * array.
  1655. *
  1656. * <p> See <em>The Java Language Specification</em>, section 8.2.
  1657. *
  1658. * @return the array of {@code Method} objects representing all the
  1659. * declared methods of this class
  1660. * @exception SecurityException
  1661. * If a security manager, <i>s</i>, is present and any of the
  1662. * following conditions is met:
  1663. *
  1664. * <ul>
  1665. *
  1666. * <li> invocation of
  1667. * {@link SecurityManager#checkMemberAccess
  1668. * s.checkMemberAccess(this, Member.DECLARED)} denies
  1669. * access to the declared methods within this class
  1670. *
  1671. * <li> the caller's class loader is not the same as or an
  1672. * ancestor of the class loader for the current class and
  1673. * invocation of {@link SecurityManager#checkPackageAccess
  1674. * s.checkPackageAccess()} denies access to the package
  1675. * of this class
  1676. *
  1677. * </ul>
  1678. *
  1679. * @since JDK1.1
  1680. */
  1681. public Method[] getDeclaredMethods() throws SecurityException {
  1682. // be very careful not to change the stack depth of this
  1683. // checkMemberAccess call for security reasons
  1684. // see java.lang.SecurityManager.checkMemberAccess
  1685. checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader());
  1686. return copyMethods(privateGetDeclaredMethods(false));
  1687. }
  1688. /**
  1689. * Returns an array of {@code Constructor} objects reflecting all the
  1690. * constructors declared by the class represented by this
  1691. * {@code Class} object. These are public, protected, default
  1692. * (package) access, and private constructors. The elements in the array
  1693. * returned are not sorted and are not in any particular order. If the
  1694. * class has a default constructor, it is included in the returned array.
  1695. * This method returns an array of length 0 if this {@code Class}
  1696. * object represents an interface, a primitive type, an array class, or
  1697. * void.
  1698. *
  1699. * <p> See <em>The Java Language Specification</em>, section 8.2.
  1700. *
  1701. * @return the array of {@code Constructor} objects representing all the
  1702. * declared constructors of this class
  1703. * @exception SecurityException
  1704. * If a security manager, <i>s</i>, is present and any of the
  1705. * following conditions is met:
  1706. *
  1707. * <ul>
  1708. *
  1709. * <li> invocation of
  1710. * {@link SecurityManager#checkMemberAccess
  1711. * s.checkMemberAccess(this, Member.DECLARED)} denies
  1712. * access to the declared constructors within this class
  1713. *
  1714. * <li> the caller's class loader is not the same as or an
  1715. * ancestor of the class loader for the current class and
  1716. * invocation of {@link SecurityManager#checkPackageAccess
  1717. * s.checkPackageAccess()} denies access to the package
  1718. * of this class
  1719. *
  1720. * </ul>
  1721. *
  1722. * @since JDK1.1
  1723. */
  1724. public Constructor<?>[] getDeclaredConstructors() throws SecurityException {
  1725. // be very careful not to change the stack depth of this
  1726. // checkMemberAccess call for security reasons
  1727. // see java.lang.SecurityManager.checkMemberAccess
  1728. checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader());
  1729. return copyConstructors(privateGetDeclaredConstructors(false));
  1730. }
  1731. /**
  1732. * Returns a {@code Field} object that reflects the specified declared
  1733. * field of the class or interface represented by this {@code Class}
  1734. * object. The {@code name} parameter is a {@code String} that
  1735. * specifies the simple name of the desired field. Note that this method
  1736. * will not reflect the {@code length} field of an array class.
  1737. *
  1738. * @param name the name of the field
  1739. * @return the {@code Field} object for the specified field in this
  1740. * class
  1741. * @exception NoSuchFieldException if a field with the specified name is
  1742. * not found.
  1743. * @exception NullPointerException if {@code name} is {@code null}
  1744. * @exception SecurityException
  1745. * If a security manager, <i>s</i>, is present and any of the
  1746. * following conditions is met:
  1747. *
  1748. * <ul>
  1749. *
  1750. * <li> invocation of
  1751. * {@link SecurityManager#checkMemberAccess
  1752. * s.checkMemberAccess(this, Member.DECLARED)} denies
  1753. * access to the declared field
  1754. *
  1755. * <li> the caller's class loader is not the same as or an
  1756. * ancestor of the class loader for the current class and
  1757. * invocation of {@link SecurityManager#checkPackageAccess
  1758. * s.checkPackageAccess()} denies access to the package
  1759. * of this class
  1760. *
  1761. * </ul>
  1762. *
  1763. * @since JDK1.1
  1764. */
  1765. public Field getDeclaredField(String name)
  1766. throws NoSuchFieldException, SecurityException {
  1767. // be very careful not to change the stack depth of this
  1768. // checkMemberAccess call for security reasons
  1769. // see java.lang.SecurityManager.checkMemberAccess
  1770. checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader());
  1771. Field field = searchFields(privateGetDeclaredFields(false), name);
  1772. if (field == null) {
  1773. throw new NoSuchFieldException(name);
  1774. }
  1775. return field;
  1776. }
  1777. /**
  1778. * Returns a {@code Method} object that reflects the specified
  1779. * declared method of the class or interface represented by this
  1780. * {@code Class} object. The {@code name} parameter is a
  1781. * {@code String} that specifies the simple name of the desired
  1782. * method, and the {@code parameterTypes} parameter is an array of
  1783. * {@code Class} objects that identify the method's formal parameter
  1784. * types, in declared order. If more than one method with the same
  1785. * parameter types is declared in a class, and one of these methods has a
  1786. * return type that is more specific than any of the others, that method is
  1787. * returned; otherwise one of the methods is chosen arbitrarily. If the
  1788. * name is "&lt;init&gt;"or "&lt;clinit&gt;" a {@code NoSuchMethodException}
  1789. * is raised.
  1790. *
  1791. * @param name the name of the method
  1792. * @param parameterTypes the parameter array
  1793. * @return the {@code Method} object for the method of this class
  1794. * matching the specified name and parameters
  1795. * @exception NoSuchMethodException if a matching method is not found.
  1796. * @exception NullPointerException if {@code name} is {@code null}
  1797. * @exception SecurityException
  1798. * If a security manager, <i>s</i>, is present and any of the
  1799. * following conditions is met:
  1800. *
  1801. * <ul>
  1802. *
  1803. * <li> invocation of
  1804. * {@link SecurityManager#checkMemberAccess
  1805. * s.checkMemberAccess(this, Member.DECLARED)} denies
  1806. * access to the declared method
  1807. *
  1808. * <li> the caller's class loader is not the same as or an
  1809. * ancestor of the class loader for the current class and
  1810. * invocation of {@link SecurityManager#checkPackageAccess
  1811. * s.checkPackageAccess()} denies access to the package
  1812. * of this class
  1813. *
  1814. * </ul>
  1815. *
  1816. * @since JDK1.1
  1817. */
  1818. public Method getDeclaredMethod(String name, Class<?>... parameterTypes)
  1819. throws NoSuchMethodException, SecurityException {
  1820. // be very careful not to change the stack depth of this
  1821. // checkMemberAccess call for security reasons
  1822. // see java.lang.SecurityManager.checkMemberAccess
  1823. checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader());
  1824. Method method = searchMethods(privateGetDeclaredMethods(false), name, parameterTypes);
  1825. if (method == null) {
  1826. throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes));
  1827. }
  1828. return method;
  1829. }
  1830. /**
  1831. * Returns a {@code Constructor} object that reflects the specified
  1832. * constructor of the class or interface represented by this
  1833. * {@code Class} object. The {@code parameterTypes} parameter is
  1834. * an array of {@code Class} objects that identify the constructor's
  1835. * formal parameter types, in declared order.
  1836. *
  1837. * If this {@code Class} object represents an inner class
  1838. * declared in a non-static context, the formal parameter types
  1839. * include the explicit enclosing instance as the first parameter.
  1840. *
  1841. * @param parameterTypes the parameter array
  1842. * @return The {@code Constructor} object for the constructor with the
  1843. * specified parameter list
  1844. * @exception NoSuchMethodException if a matching method is not found.
  1845. * @exception SecurityException
  1846. * If a security manager, <i>s</i>, is present and any of the
  1847. * following conditions is met:
  1848. *
  1849. * <ul>
  1850. *
  1851. * <li> invocation of
  1852. * {@link SecurityManager#checkMemberAccess
  1853. * s.checkMemberAccess(this, Member.DECLARED)} denies
  1854. * access to the declared constructor
  1855. *
  1856. * <li> the caller's class loader is not the same as or an
  1857. * ancestor of the class loader for the current class and
  1858. * invocation of {@link SecurityManager#checkPackageAccess
  1859. * s.checkPackageAccess()} denies access to the package
  1860. * of this class
  1861. *
  1862. * </ul>
  1863. *
  1864. * @since JDK1.1
  1865. */
  1866. public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)
  1867. throws NoSuchMethodException, SecurityException {
  1868. // be very careful not to change the stack depth of this
  1869. // checkMemberAccess call for security reasons
  1870. // see java.lang.SecurityManager.checkMemberAccess
  1871. checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader());
  1872. return getConstructor0(parameterTypes, Member.DECLARED);
  1873. }
  1874. /**
  1875. * Finds a resource with a given name. The rules for searching resources
  1876. * associated with a given class are implemented by the defining
  1877. * {@linkplain ClassLoader class loader} of the class. This method
  1878. * delegates to this object's class loader. If this object was loaded by
  1879. * the bootstrap class loader, the method delegates to {@link
  1880. * ClassLoader#getSystemResourceAsStream}.
  1881. *
  1882. * <p> Before delegation, an absolute resource name is constructed from the
  1883. * given resource name using this algorithm:
  1884. *
  1885. * <ul>
  1886. *
  1887. * <li> If the {@code name} begins with a {@code '/'}
  1888. * (<tt>'&#92;u002f'</tt>), then the absolute name of the resource is the
  1889. * portion of the {@code name} following the {@code '/'}.
  1890. *
  1891. * <li> Otherwise, the absolute name is of the following form:
  1892. *
  1893. * <blockquote>
  1894. * {@code modified_package_name/name}
  1895. * </blockquote>
  1896. *
  1897. * <p> Where the {@code modified_package_name} is the package name of this
  1898. * object with {@code '/'} substituted for {@code '.'}
  1899. * (<tt>'&#92;u002e'</tt>).
  1900. *
  1901. * </ul>
  1902. *
  1903. * @param name name of the desired resource
  1904. * @return A {@link java.io.InputStream} object or {@code null} if
  1905. * no resource with this name is found
  1906. * @throws NullPointerException If {@code name} is {@code null}
  1907. * @since JDK1.1
  1908. */
  1909. public InputStream getResourceAsStream(String name) {
  1910. name = resolveName(name);
  1911. ClassLoader cl = getClassLoader0();
  1912. if (cl==null) {
  1913. // A system class.
  1914. return ClassLoader.getSystemResourceAsStream(name);
  1915. }
  1916. return cl.getResourceAsStream(name);
  1917. }
  1918. /**
  1919. * Finds a resource with a given name. The rules for searching resources
  1920. * associated with a given class are implemented by the defining
  1921. * {@linkplain ClassLoader class loader} of the class. This method
  1922. * delegates to this object's class loader. If this object was loaded by
  1923. * the bootstrap class loader, the method delegates to {@link
  1924. * ClassLoader#getSystemResource}.
  1925. *
  1926. * <p> Before delegation, an absolute resource name is constructed from the
  1927. * given resource name using this algorithm:
  1928. *
  1929. * <ul>
  1930. *
  1931. * <li> If the {@code name} begins with a {@code '/'}
  1932. * (<tt>'&#92;u002f'</tt>), then the absolute name of the resource is the
  1933. * portion of the {@code name} following the {@code '/'}.
  1934. *
  1935. * <li> Otherwise, the absolute name is of the following form:
  1936. *
  1937. * <blockquote>
  1938. * {@code modified_package_name/name}
  1939. * </blockquote>
  1940. *
  1941. * <p> Where the {@code modified_package_name} is the package name of this
  1942. * object with {@code '/'} substituted for {@code '.'}
  1943. * (<tt>'&#92;u002e'</tt>).
  1944. *
  1945. * </ul>
  1946. *
  1947. * @param name name of the desired resource
  1948. * @return A {@link java.net.URL} object or {@code null} if no
  1949. * resource with this name is found
  1950. * @since JDK1.1
  1951. */
  1952. public java.net.URL getResource(String name) {
  1953. name = resolveName(name);
  1954. ClassLoader cl = getClassLoader0();
  1955. if (cl==null) {
  1956. // A system class.
  1957. return ClassLoader.getSystemResource(name);
  1958. }
  1959. return cl.getResource(name);
  1960. }
  1961. /** protection domain returned when the internal domain is null */
  1962. private static java.security.ProtectionDomain allPermDomain;
  1963. /**
  1964. * Returns the {@code ProtectionDomain} of this class. If there is a
  1965. * security manager installed, this method first calls the security
  1966. * manager's {@code checkPermission} method with a
  1967. * {@code RuntimePermission("getProtectionDomain")} permission to
  1968. * ensure it's ok to get the
  1969. * {@code ProtectionDomain}.
  1970. *
  1971. * @return the ProtectionDomain of this class
  1972. *
  1973. * @throws SecurityException
  1974. * if a security manager exists and its
  1975. * {@code checkPermission} method doesn't allow
  1976. * getting the ProtectionDomain.
  1977. *
  1978. * @see java.security.ProtectionDomain
  1979. * @see SecurityManager#checkPermission
  1980. * @see java.lang.RuntimePermission
  1981. * @since 1.2
  1982. */
  1983. public java.security.ProtectionDomain getProtectionDomain() {
  1984. SecurityManager sm = System.getSecurityManager();
  1985. if (sm != null) {
  1986. sm.checkPermission(SecurityConstants.GET_PD_PERMISSION);
  1987. }
  1988. java.security.ProtectionDomain pd = getProtectionDomain0();
  1989. if (pd == null) {
  1990. if (allPermDomain == null) {
  1991. java.security.Permissions perms =
  1992. new java.security.Permissions();
  1993. perms.add(SecurityConstants.ALL_PERMISSION);
  1994. allPermDomain =
  1995. new java.security.ProtectionDomain(null, perms);
  1996. }
  1997. pd = allPermDomain;
  1998. }
  1999. return pd;
  2000. }
  2001. /**
  2002. * Returns the ProtectionDomain of this class.
  2003. */
  2004. private native java.security.ProtectionDomain getProtectionDomain0();
  2005. /**
  2006. * Set the ProtectionDomain for this class. Called by
  2007. * ClassLoader.defineClass.
  2008. */
  2009. native void setProtectionDomain0(java.security.ProtectionDomain pd);
  2010. /*
  2011. * Return the Virtual Machine's Class object for the named
  2012. * primitive type.
  2013. */
  2014. static native Class getPrimitiveClass(String name);
  2015. /*
  2016. * Check if client is allowed to access members. If access is denied,
  2017. * throw a SecurityException.
  2018. *
  2019. * Be very careful not to change the stack depth of this checkMemberAccess
  2020. * call for security reasons.
  2021. * See java.lang.SecurityManager.checkMemberAccess.
  2022. *
  2023. * <p> Default policy: allow all clients access with normal Java access
  2024. * control.
  2025. */
  2026. private void checkMemberAccess(int which, ClassLoader ccl) {
  2027. SecurityManager s = System.getSecurityManager();
  2028. if (s != null) {
  2029. s.checkMemberAccess(this, which);
  2030. ClassLoader cl = getClassLoader0();
  2031. if ((ccl != null) && (ccl != cl) &&
  2032. ((cl == null) || !cl.isAncestor(ccl))) {
  2033. String name = this.getName();
  2034. int i = name.lastIndexOf('.');
  2035. if (i != -1) {
  2036. s.checkPackageAccess(name.substring(0, i));
  2037. }
  2038. }
  2039. }
  2040. }
  2041. /**
  2042. * Add a package name prefix if the name is not absolute Remove leading "/"
  2043. * if name is absolute
  2044. */
  2045. private String resolveName(String name) {
  2046. if (name == null) {
  2047. return name;
  2048. }
  2049. if (!name.startsWith("/")) {
  2050. Class<?> c = this;
  2051. while (c.isArray()) {
  2052. c = c.getComponentType();
  2053. }
  2054. String baseName = c.getName();
  2055. int index = baseName.lastIndexOf('.');
  2056. if (index != -1) {
  2057. name = baseName.substring(0, index).replace('.', '/')
  2058. +"/"+name;
  2059. }
  2060. } else {
  2061. name = name.substring(1);
  2062. }
  2063. return name;
  2064. }
  2065. /**
  2066. * Reflection support.
  2067. */
  2068. // Caches for certain reflective results
  2069. private static boolean useCaches = true;
  2070. private volatile transient SoftReference<Field[]> declaredFields;
  2071. private volatile transient SoftReference<Field[]> publicFields;
  2072. private volatile transient SoftReference<Method[]> declaredMethods;
  2073. private volatile transient SoftReference<Method[]> publicMethods;
  2074. private volatile transient SoftReference<Constructor<T>[]> declaredConstructors;
  2075. private volatile transient SoftReference<Constructor<T>[]> publicConstructors;
  2076. // Intermediate results for getFields and getMethods
  2077. private volatile transient SoftReference<Field[]> declaredPublicFields;
  2078. private volatile transient SoftReference<Method[]> declaredPublicMethods;
  2079. // Incremented by the VM on each call to JVM TI RedefineClasses()
  2080. // that redefines this class or a superclass.
  2081. private volatile transient int classRedefinedCount = 0;
  2082. // Value of classRedefinedCount when we last cleared the cached values
  2083. // that are sensitive to class redefinition.
  2084. private volatile transient int lastRedefinedCount = 0;
  2085. // Clears cached values that might possibly have been obsoleted by
  2086. // a class redefinition.
  2087. private void clearCachesOnClassRedefinition() {
  2088. if (lastRedefinedCount != classRedefinedCount) {
  2089. declaredFields = publicFields = declaredPublicFields = null;
  2090. declaredMethods = publicMethods = declaredPublicMethods = null;
  2091. declaredConstructors = publicConstructors = null;
  2092. annotations = declaredAnnotations = null;
  2093. // Use of "volatile" (and synchronization by caller in the case
  2094. // of annotations) ensures that no thread sees the update to
  2095. // lastRedefinedCount before seeing the caches cleared.
  2096. // We do not guard against brief windows during which multiple
  2097. // threads might redundantly work to fill an empty cache.
  2098. lastRedefinedCount = classRedefinedCount;
  2099. }
  2100. }
  2101. // Generic signature handling
  2102. private native String getGenericSignature();
  2103. // Generic info repository; lazily initialized
  2104. private transient ClassRepository genericInfo;
  2105. // accessor for factory
  2106. private GenericsFactory getFactory() {
  2107. // create scope and factory
  2108. return CoreReflectionFactory.make(this, ClassScope.make(this));
  2109. }
  2110. // accessor for generic info repository
  2111. private ClassRepository getGenericInfo() {
  2112. // lazily initialize repository if necessary
  2113. if (genericInfo == null) {
  2114. // create and cache generic info repository
  2115. genericInfo = ClassRepository.make(getGenericSignature(),
  2116. getFactory());
  2117. }
  2118. return genericInfo; //return cached repository
  2119. }
  2120. // Annotations handling
  2121. private native byte[] getRawAnnotations();
  2122. native ConstantPool getConstantPool();
  2123. //
  2124. //
  2125. // java.lang.reflect.Field handling
  2126. //
  2127. //
  2128. // Returns an array of "root" fields. These Field objects must NOT
  2129. // be propagated to the outside world, but must instead be copied
  2130. // via ReflectionFactory.copyField.
  2131. private Field[] privateGetDeclaredFields(boolean publicOnly) {
  2132. checkInitted();
  2133. Field[] res = null;
  2134. if (useCaches) {
  2135. clearCachesOnClassRedefinition();
  2136. if (publicOnly) {
  2137. if (declaredPublicFields != null) {
  2138. res = declaredPublicFields.get();
  2139. }
  2140. } else {
  2141. if (declaredFields != null) {
  2142. res = declaredFields.get();
  2143. }
  2144. }
  2145. if (res != null) return res;
  2146. }
  2147. // No cached value available; request value from VM
  2148. res = Reflection.filterFields(this, getDeclaredFields0(publicOnly));
  2149. if (useCaches) {
  2150. if (publicOnly) {
  2151. declaredPublicFields = new SoftReference<>(res);
  2152. } else {
  2153. declaredFields = new SoftReference<>(res);
  2154. }
  2155. }
  2156. return res;
  2157. }
  2158. // Returns an array of "root" fields. These Field objects must NOT
  2159. // be propagated to the outside world, but must instead be copied
  2160. // via ReflectionFactory.copyField.
  2161. private Field[] privateGetPublicFields(Set<Class<?>> traversedInterfaces) {
  2162. checkInitted();
  2163. Field[] res = null;
  2164. if (useCaches) {
  2165. clearCachesOnClassRedefinition();
  2166. if (publicFields != null) {
  2167. res = publicFields.get();
  2168. }
  2169. if (res != null) return res;
  2170. }
  2171. // No cached value available; compute value recursively.
  2172. // Traverse in correct order for getField().
  2173. List<Field> fields = new ArrayList<>();
  2174. if (traversedInterfaces == null) {
  2175. traversedInterfaces = new HashSet<>();
  2176. }
  2177. // Local fields
  2178. Field[] tmp = privateGetDeclaredFields(true);
  2179. addAll(fields, tmp);
  2180. // Direct superinterfaces, recursively
  2181. for (Class<?> c : getInterfaces()) {
  2182. if (!traversedInterfaces.contains(c)) {
  2183. traversedInterfaces.add(c);
  2184. addAll(fields, c.privateGetPublicFields(traversedInterfaces));
  2185. }
  2186. }
  2187. // Direct superclass, recursively
  2188. if (!isInterface()) {
  2189. Class<?> c = getSuperclass();
  2190. if (c != null) {
  2191. addAll(fields, c.privateGetPublicFields(traversedInterfaces));
  2192. }
  2193. }
  2194. res = new Field[fields.size()];
  2195. fields.toArray(res);
  2196. if (useCaches) {
  2197. publicFields = new SoftReference<>(res);
  2198. }
  2199. return res;
  2200. }
  2201. private static void addAll(Collection<Field> c, Field[] o) {
  2202. for (int i = 0; i < o.length; i++) {
  2203. c.add(o[i]);
  2204. }
  2205. }
  2206. //
  2207. //
  2208. // java.lang.reflect.Constructor handling
  2209. //
  2210. //
  2211. // Returns an array of "root" constructors. These Constructor
  2212. // objects must NOT be propagated to the outside world, but must
  2213. // instead be copied via ReflectionFactory.copyConstructor.
  2214. private Constructor<T>[] privateGetDeclaredConstructors(boolean publicOnly) {
  2215. checkInitted();
  2216. Constructor<T>[] res = null;
  2217. if (useCaches) {
  2218. clearCachesOnClassRedefinition();
  2219. if (publicOnly) {
  2220. if (publicConstructors != null) {
  2221. res = publicConstructors.get();
  2222. }
  2223. } else {
  2224. if (declaredConstructors != null) {
  2225. res = declaredConstructors.get();
  2226. }
  2227. }
  2228. if (res != null) return res;
  2229. }
  2230. // No cached value available; request value from VM
  2231. if (isInterface()) {
  2232. res = new Constructor[0];
  2233. } else {
  2234. res = getDeclaredConstructors0(publicOnly);
  2235. }
  2236. if (useCaches) {
  2237. if (publicOnly) {
  2238. publicConstructors = new SoftReference<>(res);
  2239. } else {
  2240. declaredConstructors = new SoftReference<>(res);
  2241. }
  2242. }
  2243. return res;
  2244. }
  2245. //
  2246. //
  2247. // java.lang.reflect.Method handling
  2248. //
  2249. //
  2250. // Returns an array of "root" methods. These Method objects must NOT
  2251. // be propagated to the outside world, but must instead be copied
  2252. // via ReflectionFactory.copyMethod.
  2253. private Method[] privateGetDeclaredMethods(boolean publicOnly) {
  2254. checkInitted();
  2255. Method[] res = null;
  2256. if (useCaches) {
  2257. clearCachesOnClassRedefinition();
  2258. if (publicOnly) {
  2259. if (declaredPublicMethods != null) {
  2260. res = declaredPublicMethods.get();
  2261. }
  2262. } else {
  2263. if (declaredMethods != null) {
  2264. res = declaredMethods.get();
  2265. }
  2266. }
  2267. if (res != null) return res;
  2268. }
  2269. // No cached value available; request value from VM
  2270. res = Reflection.filterMethods(this, getDeclaredMethods0(publicOnly));
  2271. if (useCaches) {
  2272. if (publicOnly) {
  2273. declaredPublicMethods = new SoftReference<>(res);
  2274. } else {
  2275. declaredMethods = new SoftReference<>(res);
  2276. }
  2277. }
  2278. return res;
  2279. }
  2280. static class MethodArray {
  2281. private Method[] methods;
  2282. private int length;
  2283. MethodArray() {
  2284. methods = new Method[20];
  2285. length = 0;
  2286. }
  2287. void add(Method m) {
  2288. if (length == methods.length) {
  2289. methods = Arrays.copyOf(methods, 2 * methods.length);
  2290. }
  2291. methods[length++] = m;
  2292. }
  2293. void addAll(Method[] ma) {
  2294. for (int i = 0; i < ma.length; i++) {
  2295. add(ma[i]);
  2296. }
  2297. }
  2298. void addAll(MethodArray ma) {
  2299. for (int i = 0; i < ma.length(); i++) {
  2300. add(ma.get(i));
  2301. }
  2302. }
  2303. void addIfNotPresent(Method newMethod) {
  2304. for (int i = 0; i < length; i++) {
  2305. Method m = methods[i];
  2306. if (m == newMethod || (m != null && m.equals(newMethod))) {
  2307. return;
  2308. }
  2309. }
  2310. add(newMethod);
  2311. }
  2312. void addAllIfNotPresent(MethodArray newMethods) {
  2313. for (int i = 0; i < newMethods.length(); i++) {
  2314. Method m = newMethods.get(i);
  2315. if (m != null) {
  2316. addIfNotPresent(m);
  2317. }
  2318. }
  2319. }
  2320. int length() {
  2321. return length;
  2322. }
  2323. Method get(int i) {
  2324. return methods[i];
  2325. }
  2326. void removeByNameAndSignature(Method toRemove) {
  2327. for (int i = 0; i < length; i++) {
  2328. Method m = methods[i];
  2329. if (m != null &&
  2330. m.getReturnType() == toRemove.getReturnType() &&
  2331. m.getName() == toRemove.getName() &&
  2332. arrayContentsEq(m.getParameterTypes(),
  2333. toRemove.getParameterTypes())) {
  2334. methods[i] = null;
  2335. }
  2336. }
  2337. }
  2338. void compactAndTrim() {
  2339. int newPos = 0;
  2340. // Get rid of null slots
  2341. for (int pos = 0; pos < length; pos++) {
  2342. Method m = methods[pos];
  2343. if (m != null) {
  2344. if (pos != newPos) {
  2345. methods[newPos] = m;
  2346. }
  2347. newPos++;
  2348. }
  2349. }
  2350. if (newPos != methods.length) {
  2351. methods = Arrays.copyOf(methods, newPos);
  2352. }
  2353. }
  2354. Method[] getArray() {
  2355. return methods;
  2356. }
  2357. }
  2358. // Returns an array of "root" methods. These Method objects must NOT
  2359. // be propagated to the outside world, but must instead be copied
  2360. // via ReflectionFactory.copyMethod.
  2361. private Method[] privateGetPublicMethods() {
  2362. checkInitted();
  2363. Method[] res = null;
  2364. if (useCaches) {
  2365. clearCachesOnClassRedefinition();
  2366. if (publicMethods != null) {
  2367. res = publicMethods.get();
  2368. }
  2369. if (res != null) return res;
  2370. }
  2371. // No cached value available; compute value recursively.
  2372. // Start by fetching public declared methods
  2373. MethodArray methods = new MethodArray();
  2374. {
  2375. Method[] tmp = privateGetDeclaredMethods(true);
  2376. methods.addAll(tmp);
  2377. }
  2378. // Now recur over superclass and direct superinterfaces.
  2379. // Go over superinterfaces first so we can more easily filter
  2380. // out concrete implementations inherited from superclasses at
  2381. // the end.
  2382. MethodArray inheritedMethods = new MethodArray();
  2383. Class<?>[] interfaces = getInterfaces();
  2384. for (int i = 0; i < interfaces.length; i++) {
  2385. inheritedMethods.addAll(interfaces[i].privateGetPublicMethods());
  2386. }
  2387. if (!isInterface()) {
  2388. Class<?> c = getSuperclass();
  2389. if (c != null) {
  2390. MethodArray supers = new MethodArray();
  2391. supers.addAll(c.privateGetPublicMethods());
  2392. // Filter out concrete implementations of any
  2393. // interface methods
  2394. for (int i = 0; i < supers.length(); i++) {
  2395. Method m = supers.get(i);
  2396. if (m != null && !Modifier.isAbstract(m.getModifiers())) {
  2397. inheritedMethods.removeByNameAndSignature(m);
  2398. }
  2399. }
  2400. // Insert superclass's inherited methods before
  2401. // superinterfaces' to satisfy getMethod's search
  2402. // order
  2403. supers.addAll(inheritedMethods);
  2404. inheritedMethods = supers;
  2405. }
  2406. }
  2407. // Filter out all local methods from inherited ones
  2408. for (int i = 0; i < methods.length(); i++) {
  2409. Method m = methods.get(i);
  2410. inheritedMethods.removeByNameAndSignature(m);
  2411. }
  2412. methods.addAllIfNotPresent(inheritedMethods);
  2413. methods.compactAndTrim();
  2414. res = methods.getArray();
  2415. if (useCaches) {
  2416. publicMethods = new SoftReference<>(res);
  2417. }
  2418. return res;
  2419. }
  2420. //
  2421. // Helpers for fetchers of one field, method, or constructor
  2422. //
  2423. private Field searchFields(Field[] fields, String name) {
  2424. String internedName = name.intern();
  2425. for (int i = 0; i < fields.length; i++) {
  2426. if (fields[i].getName() == internedName) {
  2427. return getReflectionFactory().copyField(fields[i]);
  2428. }
  2429. }
  2430. return null;
  2431. }
  2432. private Field getField0(String name) throws NoSuchFieldException {
  2433. // Note: the intent is that the search algorithm this routine
  2434. // uses be equivalent to the ordering imposed by
  2435. // privateGetPublicFields(). It fetches only the declared
  2436. // public fields for each class, however, to reduce the number
  2437. // of Field objects which have to be created for the common
  2438. // case where the field being requested is declared in the
  2439. // class which is being queried.
  2440. Field res = null;
  2441. // Search declared public fields
  2442. if ((res = searchFields(privateGetDeclaredFields(true), name)) != null) {
  2443. return res;
  2444. }
  2445. // Direct superinterfaces, recursively
  2446. Class<?>[] interfaces = getInterfaces();
  2447. for (int i = 0; i < interfaces.length; i++) {
  2448. Class<?> c = interfaces[i];
  2449. if ((res = c.getField0(name)) != null) {
  2450. return res;
  2451. }
  2452. }
  2453. // Direct superclass, recursively
  2454. if (!isInterface()) {
  2455. Class<?> c = getSuperclass();
  2456. if (c != null) {
  2457. if ((res = c.getField0(name)) != null) {
  2458. return res;
  2459. }
  2460. }
  2461. }
  2462. return null;
  2463. }
  2464. private static Method searchMethods(Method[] methods,
  2465. String name,
  2466. Class<?>[] parameterTypes)
  2467. {
  2468. Method res = null;
  2469. String internedName = name.intern();
  2470. for (int i = 0; i < methods.length; i++) {
  2471. Method m = methods[i];
  2472. if (m.getName() == internedName
  2473. && arrayContentsEq(parameterTypes, m.getParameterTypes())
  2474. && (res == null
  2475. || res.getReturnType().isAssignableFrom(m.getReturnType())))
  2476. res = m;
  2477. }
  2478. return (res == null ? res : getReflectionFactory().copyMethod(res));
  2479. }
  2480. private Method getMethod0(String name, Class<?>[] parameterTypes) {
  2481. // Note: the intent is that the search algorithm this routine
  2482. // uses be equivalent to the ordering imposed by
  2483. // privateGetPublicMethods(). It fetches only the declared
  2484. // public methods for each class, however, to reduce the
  2485. // number of Method objects which have to be created for the
  2486. // common case where the method being requested is declared in
  2487. // the class which is being queried.
  2488. Method res = null;
  2489. // Search declared public methods
  2490. if ((res = searchMethods(privateGetDeclaredMethods(true),
  2491. name,
  2492. parameterTypes)) != null) {
  2493. return res;
  2494. }
  2495. // Search superclass's methods
  2496. if (!isInterface()) {
  2497. Class<? super T> c = getSuperclass();
  2498. if (c != null) {
  2499. if ((res = c.getMethod0(name, parameterTypes)) != null) {
  2500. return res;
  2501. }
  2502. }
  2503. }
  2504. // Search superinterfaces' methods
  2505. Class<?>[] interfaces = getInterfaces();
  2506. for (int i = 0; i < interfaces.length; i++) {
  2507. Class<?> c = interfaces[i];
  2508. if ((res = c.getMethod0(name, parameterTypes)) != null) {
  2509. return res;
  2510. }
  2511. }
  2512. // Not found
  2513. return null;
  2514. }
  2515. private Constructor<T> getConstructor0(Class<?>[] parameterTypes,
  2516. int which) throws NoSuchMethodException
  2517. {
  2518. Constructor<T>[] constructors = privateGetDeclaredConstructors((which == Member.PUBLIC));
  2519. for (Constructor<T> constructor : constructors) {
  2520. if (arrayContentsEq(parameterTypes,
  2521. constructor.getParameterTypes())) {
  2522. return getReflectionFactory().copyConstructor(constructor);
  2523. }
  2524. }
  2525. throw new NoSuchMethodException(getName() + ".<init>" + argumentTypesToString(parameterTypes));
  2526. }
  2527. //
  2528. // Other helpers and base implementation
  2529. //
  2530. private static boolean arrayContentsEq(Object[] a1, Object[] a2) {
  2531. if (a1 == null) {
  2532. return a2 == null || a2.length == 0;
  2533. }
  2534. if (a2 == null) {
  2535. return a1.length == 0;
  2536. }
  2537. if (a1.length != a2.length) {
  2538. return false;
  2539. }
  2540. for (int i = 0; i < a1.length; i++) {
  2541. if (a1[i] != a2[i]) {
  2542. return false;
  2543. }
  2544. }
  2545. return true;
  2546. }
  2547. private static Field[] copyFields(Field[] arg) {
  2548. Field[] out = new Field[arg.length];
  2549. ReflectionFactory fact = getReflectionFactory();
  2550. for (int i = 0; i < arg.length; i++) {
  2551. out[i] = fact.copyField(arg[i]);
  2552. }
  2553. return out;
  2554. }
  2555. private static Method[] copyMethods(Method[] arg) {
  2556. Method[] out = new Method[arg.length];
  2557. ReflectionFactory fact = getReflectionFactory();
  2558. for (int i = 0; i < arg.length; i++) {
  2559. out[i] = fact.copyMethod(arg[i]);
  2560. }
  2561. return out;
  2562. }
  2563. private static <U> Constructor<U>[] copyConstructors(Constructor<U>[] arg) {
  2564. Constructor<U>[] out = arg.clone();
  2565. ReflectionFactory fact = getReflectionFactory();
  2566. for (int i = 0; i < out.length; i++) {
  2567. out[i] = fact.copyConstructor(out[i]);
  2568. }
  2569. return out;
  2570. }
  2571. private native Field[] getDeclaredFields0(boolean publicOnly);
  2572. private native Method[] getDeclaredMethods0(boolean publicOnly);
  2573. private native Constructor<T>[] getDeclaredConstructors0(boolean publicOnly);
  2574. private native Class<?>[] getDeclaredClasses0();
  2575. private static String argumentTypesToString(Class<?>[] argTypes) {
  2576. StringBuilder buf = new StringBuilder();
  2577. buf.append("(");
  2578. if (argTypes != null) {
  2579. for (int i = 0; i < argTypes.length; i++) {
  2580. if (i > 0) {
  2581. buf.append(", ");
  2582. }
  2583. Class<?> c = argTypes[i];
  2584. buf.append((c == null) ? "null" : c.getName());
  2585. }
  2586. }
  2587. buf.append(")");
  2588. return buf.toString();
  2589. }
  2590. /** use serialVersionUID from JDK 1.1 for interoperability */
  2591. private static final long serialVersionUID = 3206093459760846163L;
  2592. /**
  2593. * Class Class is special cased within the Serialization Stream Protocol.
  2594. *
  2595. * A Class instance is written initially into an ObjectOutputStream in the
  2596. * following format:
  2597. * <pre>
  2598. * {@code TC_CLASS} ClassDescriptor
  2599. * A ClassDescriptor is a special cased serialization of
  2600. * a {@code java.io.ObjectStreamClass} instance.
  2601. * </pre>
  2602. * A new handle is generated for the initial time the class descriptor
  2603. * is written into the stream. Future references to the class descriptor
  2604. * are written as references to the initial class descriptor instance.
  2605. *
  2606. * @see java.io.ObjectStreamClass
  2607. */
  2608. private static final ObjectStreamField[] serialPersistentFields =
  2609. new ObjectStreamField[0];
  2610. /**
  2611. * Returns the assertion status that would be assigned to this
  2612. * class if it were to be initialized at the time this method is invoked.
  2613. * If this class has had its assertion status set, the most recent
  2614. * setting will be returned; otherwise, if any package default assertion
  2615. * status pertains to this class, the most recent setting for the most
  2616. * specific pertinent package default assertion status is returned;
  2617. * otherwise, if this class is not a system class (i.e., it has a
  2618. * class loader) its class loader's default assertion status is returned;
  2619. * otherwise, the system class default assertion status is returned.
  2620. * <p>
  2621. * Few programmers will have any need for this method; it is provided
  2622. * for the benefit of the JRE itself. (It allows a class to determine at
  2623. * the time that it is initialized whether assertions should be enabled.)
  2624. * Note that this method is not guaranteed to return the actual
  2625. * assertion status that was (or will be) associated with the specified
  2626. * class when it was (or will be) initialized.
  2627. *
  2628. * @return the desired assertion status of the specified class.
  2629. * @see java.lang.ClassLoader#setClassAssertionStatus
  2630. * @see java.lang.ClassLoader#setPackageAssertionStatus
  2631. * @see java.lang.ClassLoader#setDefaultAssertionStatus
  2632. * @since 1.4
  2633. */
  2634. public boolean desiredAssertionStatus() {
  2635. ClassLoader loader = getClassLoader();
  2636. // If the loader is null this is a system class, so ask the VM
  2637. if (loader == null)
  2638. return desiredAssertionStatus0(this);
  2639. // If the classloader has been initialized with the assertion
  2640. // directives, ask it. Otherwise, ask the VM.
  2641. synchronized(loader.assertionLock) {
  2642. if (loader.classAssertionStatus != null) {
  2643. return loader.desiredAssertionStatus(getName());
  2644. }
  2645. }
  2646. return desiredAssertionStatus0(this);
  2647. }
  2648. // Retrieves the desired assertion status of this class from the VM
  2649. private static native boolean desiredAssertionStatus0(Class<?> clazz);
  2650. /**
  2651. * Returns true if and only if this class was declared as an enum in the
  2652. * source code.
  2653. *
  2654. * @return true if and only if this class was declared as an enum in the
  2655. * source code
  2656. * @since 1.5
  2657. */
  2658. public boolean isEnum() {
  2659. // An enum must both directly extend java.lang.Enum and have
  2660. // the ENUM bit set; classes for specialized enum constants
  2661. // don't do the former.
  2662. return (this.getModifiers() & ENUM) != 0 &&
  2663. this.getSuperclass() == java.lang.Enum.class;
  2664. }
  2665. // Fetches the factory for reflective objects
  2666. private static ReflectionFactory getReflectionFactory() {
  2667. if (reflectionFactory == null) {
  2668. reflectionFactory =
  2669. java.security.AccessController.doPrivileged
  2670. (new sun.reflect.ReflectionFactory.GetReflectionFactoryAction());
  2671. }
  2672. return reflectionFactory;
  2673. }
  2674. private static ReflectionFactory reflectionFactory;
  2675. // To be able to query system properties as soon as they're available
  2676. private static boolean initted = false;
  2677. private static void checkInitted() {
  2678. if (initted) return;
  2679. AccessController.doPrivileged(new PrivilegedAction<Void>() {
  2680. public Void run() {
  2681. // Tests to ensure the system properties table is fully
  2682. // initialized. This is needed because reflection code is
  2683. // called very early in the initialization process (before
  2684. // command-line arguments have been parsed and therefore
  2685. // these user-settable properties installed.) We assume that
  2686. // if System.out is non-null then the System class has been
  2687. // fully initialized and that the bulk of the startup code
  2688. // has been run.
  2689. if (System.out == null) {
  2690. // java.lang.System not yet fully initialized
  2691. return null;
  2692. }
  2693. // Doesn't use Boolean.getBoolean to avoid class init.
  2694. String val =
  2695. System.getProperty("sun.reflect.noCaches");
  2696. if (val != null && val.equals("true")) {
  2697. useCaches = false;
  2698. }
  2699. initted = true;
  2700. return null;
  2701. }
  2702. });
  2703. }
  2704. /**
  2705. * Returns the elements of this enum class or null if this
  2706. * Class object does not represent an enum type.
  2707. *
  2708. * @return an array containing the values comprising the enum class
  2709. * represented by this Class object in the order they're
  2710. * declared, or null if this Class object does not
  2711. * represent an enum type
  2712. * @since 1.5
  2713. */
  2714. public T[] getEnumConstants() {
  2715. T[] values = getEnumConstantsShared();
  2716. return (values != null) ? values.clone() : null;
  2717. }
  2718. /**
  2719. * Returns the elements of this enum class or null if this
  2720. * Class object does not represent an enum type;
  2721. * identical to getEnumConstants except that the result is
  2722. * uncloned, cached, and shared by all callers.
  2723. */
  2724. T[] getEnumConstantsShared() {
  2725. if (enumConstants == null) {
  2726. if (!isEnum()) return null;
  2727. try {
  2728. final Method values = getMethod("values");
  2729. java.security.AccessController.doPrivileged(
  2730. new java.security.PrivilegedAction<Void>() {
  2731. public Void run() {
  2732. values.setAccessible(true);
  2733. return null;
  2734. }
  2735. });
  2736. enumConstants = (T[])values.invoke(null);
  2737. }
  2738. // These can happen when users concoct enum-like classes
  2739. // that don't comply with the enum spec.
  2740. catch (InvocationTargetException | NoSuchMethodException |
  2741. IllegalAccessException ex) { return null; }
  2742. }
  2743. return enumConstants;
  2744. }
  2745. private volatile transient T[] enumConstants = null;
  2746. /**
  2747. * Returns a map from simple name to enum constant. This package-private
  2748. * method is used internally by Enum to implement
  2749. * public static <T extends Enum<T>> T valueOf(Class<T>, String)
  2750. * efficiently. Note that the map is returned by this method is
  2751. * created lazily on first use. Typically it won't ever get created.
  2752. */
  2753. Map<String, T> enumConstantDirectory() {
  2754. if (enumConstantDirectory == null) {
  2755. T[] universe = getEnumConstantsShared();
  2756. if (universe == null)
  2757. throw new IllegalArgumentException(
  2758. getName() + " is not an enum type");
  2759. Map<String, T> m = new HashMap<>(2 * universe.length);
  2760. for (T constant : universe)
  2761. m.put(((Enum<?>)constant).name(), constant);
  2762. enumConstantDirectory = m;
  2763. }
  2764. return enumConstantDirectory;
  2765. }
  2766. private volatile transient Map<String, T> enumConstantDirectory = null;
  2767. /**
  2768. * Casts an object to the class or interface represented
  2769. * by this {@code Class} object.
  2770. *
  2771. * @param obj the object to be cast
  2772. * @return the object after casting, or null if obj is null
  2773. *
  2774. * @throws ClassCastException if the object is not
  2775. * null and is not assignable to the type T.
  2776. *
  2777. * @since 1.5
  2778. */
  2779. public T cast(Object obj) {
  2780. if (obj != null && !isInstance(obj))
  2781. throw new ClassCastException(cannotCastMsg(obj));
  2782. return (T) obj;
  2783. }
  2784. private String cannotCastMsg(Object obj) {
  2785. return "Cannot cast " + obj.getClass().getName() + " to " + getName();
  2786. }
  2787. /**
  2788. * Casts this {@code Class} object to represent a subclass of the class
  2789. * represented by the specified class object. Checks that that the cast
  2790. * is valid, and throws a {@code ClassCastException} if it is not. If
  2791. * this method succeeds, it always returns a reference to this class object.
  2792. *
  2793. * <p>This method is useful when a client needs to "narrow" the type of
  2794. * a {@code Class} object to pass it to an API that restricts the
  2795. * {@code Class} objects that it is willing to accept. A cast would
  2796. * generate a compile-time warning, as the correctness of the cast
  2797. * could not be checked at runtime (because generic types are implemented
  2798. * by erasure).
  2799. *
  2800. * @return this {@code Class} object, cast to represent a subclass of
  2801. * the specified class object.
  2802. * @throws ClassCastException if this {@code Class} object does not
  2803. * represent a subclass of the specified class (here "subclass" includes
  2804. * the class itself).
  2805. * @since 1.5
  2806. */
  2807. public <U> Class<? extends U> asSubclass(Class<U> clazz) {
  2808. if (clazz.isAssignableFrom(this))
  2809. return (Class<? extends U>) this;
  2810. else
  2811. throw new ClassCastException(this.toString());
  2812. }
  2813. /**
  2814. * @throws NullPointerException {@inheritDoc}
  2815. * @since 1.5
  2816. */
  2817. public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {
  2818. if (annotationClass == null)
  2819. throw new NullPointerException();
  2820. initAnnotationsIfNecessary();
  2821. return (A) annotations.get(annotationClass);
  2822. }
  2823. /**
  2824. * @throws NullPointerException {@inheritDoc}
  2825. * @since 1.5
  2826. */
  2827. public boolean isAnnotationPresent(
  2828. Class<? extends Annotation> annotationClass) {
  2829. if (annotationClass == null)
  2830. throw new NullPointerException();
  2831. return getAnnotation(annotationClass) != null;
  2832. }
  2833. /**
  2834. * @since 1.5
  2835. */
  2836. public Annotation[] getAnnotations() {
  2837. initAnnotationsIfNecessary();
  2838. return AnnotationParser.toArray(annotations);
  2839. }
  2840. /**
  2841. * @since 1.5
  2842. */
  2843. public Annotation[] getDeclaredAnnotations() {
  2844. initAnnotationsIfNecessary();
  2845. return AnnotationParser.toArray(declaredAnnotations);
  2846. }
  2847. // Annotations cache
  2848. private transient Map<Class<? extends Annotation>, Annotation> annotations;
  2849. private transient Map<Class<? extends Annotation>, Annotation> declaredAnnotations;
  2850. private synchronized void initAnnotationsIfNecessary() {
  2851. clearCachesOnClassRedefinition();
  2852. if (annotations != null)
  2853. return;
  2854. declaredAnnotations = AnnotationParser.parseAnnotations(
  2855. getRawAnnotations(), getConstantPool(), this);
  2856. Class<?> superClass = getSuperclass();
  2857. if (superClass == null) {
  2858. annotations = declaredAnnotations;
  2859. } else {
  2860. annotations = new HashMap<>();
  2861. superClass.initAnnotationsIfNecessary();
  2862. for (Map.Entry<Class<? extends Annotation>, Annotation> e : superClass.annotations.entrySet()) {
  2863. Class<? extends Annotation> annotationClass = e.getKey();
  2864. if (AnnotationType.getInstance(annotationClass).isInherited())
  2865. annotations.put(annotationClass, e.getValue());
  2866. }
  2867. annotations.putAll(declaredAnnotations);
  2868. }
  2869. }
  2870. // Annotation types cache their internal (AnnotationType) form
  2871. private AnnotationType annotationType;
  2872. void setAnnotationType(AnnotationType type) {
  2873. annotationType = type;
  2874. }
  2875. AnnotationType getAnnotationType() {
  2876. return annotationType;
  2877. }
  2878. }