PageRenderTime 71ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://bitbucket.org/sreilly/openjdk7u-jdk
Java | 3122 lines | 1115 code | 236 blank | 1771 comment | 337 complexity | 4ef7dd84c45093c89d371bc4a934156a MD5 | raw file
Possible License(s): GPL-2.0, BSD-3-Clause-No-Nuclear-License-2014, LGPL-3.0
  1. /*
  2. * Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved.
  3. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4. *
  5. * This code is free software; you can redistribute it and/or modify it
  6. * under the terms of the GNU General Public License version 2 only, as
  7. * published by the Free Software Foundation. Oracle designates this
  8. * particular file as subject to the "Classpath" exception as provided
  9. * by Oracle in the LICENSE file that accompanied this code.
  10. *
  11. * This code is distributed in the hope that it will be useful, but WITHOUT
  12. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13. * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
  14. * version 2 for more details (a copy is included in the LICENSE file that
  15. * accompanied this code).
  16. *
  17. * You should have received a copy of the GNU General Public License version
  18. * 2 along with this work; if not, write to the Free Software Foundation,
  19. * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20. *
  21. * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22. * or visit www.oracle.com if you need additional information or have any
  23. * questions.
  24. */
  25. package java.lang;
  26. import java.lang.reflect.Array;
  27. import java.lang.reflect.GenericArrayType;
  28. import java.lang.reflect.Member;
  29. import java.lang.reflect.Field;
  30. import java.lang.reflect.Method;
  31. import java.lang.reflect.Constructor;
  32. import java.lang.reflect.GenericDeclaration;
  33. import java.lang.reflect.Modifier;
  34. import java.lang.reflect.Type;
  35. import java.lang.reflect.TypeVariable;
  36. import java.lang.reflect.InvocationTargetException;
  37. import java.lang.ref.SoftReference;
  38. import java.io.InputStream;
  39. import java.io.ObjectStreamField;
  40. import java.security.AccessController;
  41. import java.security.PrivilegedAction;
  42. import java.util.ArrayList;
  43. import java.util.Arrays;
  44. import java.util.Collection;
  45. import java.util.HashSet;
  46. import java.util.Iterator;
  47. import java.util.List;
  48. import java.util.LinkedList;
  49. import java.util.LinkedHashSet;
  50. import java.util.Set;
  51. import java.util.Map;
  52. import java.util.HashMap;
  53. import sun.misc.Unsafe;
  54. import sun.reflect.ConstantPool;
  55. import sun.reflect.Reflection;
  56. import sun.reflect.ReflectionFactory;
  57. import sun.reflect.SignatureIterator;
  58. import sun.reflect.generics.factory.CoreReflectionFactory;
  59. import sun.reflect.generics.factory.GenericsFactory;
  60. import sun.reflect.generics.repository.ClassRepository;
  61. import sun.reflect.generics.repository.MethodRepository;
  62. import sun.reflect.generics.repository.ConstructorRepository;
  63. import sun.reflect.generics.scope.ClassScope;
  64. import sun.security.util.SecurityConstants;
  65. import java.lang.annotation.Annotation;
  66. import sun.reflect.annotation.*;
  67. /**
  68. * Instances of the class {@code Class} represent classes and
  69. * interfaces in a running Java application. An enum is a kind of
  70. * class and an annotation is a kind of interface. Every array also
  71. * belongs to a class that is reflected as a {@code Class} object
  72. * that is shared by all arrays with the same element type and number
  73. * of dimensions. The primitive Java types ({@code boolean},
  74. * {@code byte}, {@code char}, {@code short},
  75. * {@code int}, {@code long}, {@code float}, and
  76. * {@code double}), and the keyword {@code void} are also
  77. * represented as {@code Class} objects.
  78. *
  79. * <p> {@code Class} has no public constructor. Instead {@code Class}
  80. * objects are constructed automatically by the Java Virtual Machine as classes
  81. * are loaded and by calls to the {@code defineClass} method in the class
  82. * loader.
  83. *
  84. * <p> The following example uses a {@code Class} object to print the
  85. * class name of an object:
  86. *
  87. * <p> <blockquote><pre>
  88. * void printClassName(Object obj) {
  89. * System.out.println("The class of " + obj +
  90. * " is " + obj.getClass().getName());
  91. * }
  92. * </pre></blockquote>
  93. *
  94. * <p> It is also possible to get the {@code Class} object for a named
  95. * type (or for void) using a class literal. See Section 15.8.2 of
  96. * <cite>The Java&trade; Language Specification</cite>.
  97. * For example:
  98. *
  99. * <p> <blockquote>
  100. * {@code System.out.println("The name of class Foo is: "+Foo.class.getName());}
  101. * </blockquote>
  102. *
  103. * @param <T> the type of the class modeled by this {@code Class}
  104. * object. For example, the type of {@code String.class} is {@code
  105. * Class<String>}. Use {@code Class<?>} if the class being modeled is
  106. * unknown.
  107. *
  108. * @author unascribed
  109. * @see java.lang.ClassLoader#defineClass(byte[], int, int)
  110. * @since JDK1.0
  111. */
  112. public final
  113. class Class<T> implements java.io.Serializable,
  114. java.lang.reflect.GenericDeclaration,
  115. java.lang.reflect.Type,
  116. java.lang.reflect.AnnotatedElement {
  117. private static final int ANNOTATION= 0x00002000;
  118. private static final int ENUM = 0x00004000;
  119. private static final int SYNTHETIC = 0x00001000;
  120. private static native void registerNatives();
  121. static {
  122. registerNatives();
  123. }
  124. /*
  125. * Constructor. Only the Java Virtual Machine creates Class
  126. * objects.
  127. */
  128. private Class() {}
  129. /**
  130. * Converts the object to a string. The string representation is the
  131. * string "class" or "interface", followed by a space, and then by the
  132. * fully qualified name of the class in the format returned by
  133. * {@code getName}. If this {@code Class} object represents a
  134. * primitive type, this method returns the name of the primitive type. If
  135. * this {@code Class} object represents void this method returns
  136. * "void".
  137. *
  138. * @return a string representation of this class object.
  139. */
  140. public String toString() {
  141. return (isInterface() ? "interface " : (isPrimitive() ? "" : "class "))
  142. + getName();
  143. }
  144. /**
  145. * Returns the {@code Class} object associated with the class or
  146. * interface with the given string name. Invoking this method is
  147. * equivalent to:
  148. *
  149. * <blockquote>
  150. * {@code Class.forName(className, true, currentLoader)}
  151. * </blockquote>
  152. *
  153. * where {@code currentLoader} denotes the defining class loader of
  154. * the current class.
  155. *
  156. * <p> For example, the following code fragment returns the
  157. * runtime {@code Class} descriptor for the class named
  158. * {@code java.lang.Thread}:
  159. *
  160. * <blockquote>
  161. * {@code Class t = Class.forName("java.lang.Thread")}
  162. * </blockquote>
  163. * <p>
  164. * A call to {@code forName("X")} causes the class named
  165. * {@code X} to be initialized.
  166. *
  167. * @param className the fully qualified name of the desired class.
  168. * @return the {@code Class} object for the class with the
  169. * specified name.
  170. * @exception LinkageError if the linkage fails
  171. * @exception ExceptionInInitializerError if the initialization provoked
  172. * by this method fails
  173. * @exception ClassNotFoundException if the class cannot be located
  174. */
  175. public static Class<?> forName(String className)
  176. throws ClassNotFoundException {
  177. return forName0(className, true, ClassLoader.getCallerClassLoader());
  178. }
  179. /**
  180. * Returns the {@code Class} object associated with the class or
  181. * interface with the given string name, using the given class loader.
  182. * Given the fully qualified name for a class or interface (in the same
  183. * format returned by {@code getName}) this method attempts to
  184. * locate, load, and link the class or interface. The specified class
  185. * loader is used to load the class or interface. If the parameter
  186. * {@code loader} is null, the class is loaded through the bootstrap
  187. * class loader. The class is initialized only if the
  188. * {@code initialize} parameter is {@code true} and if it has
  189. * not been initialized earlier.
  190. *
  191. * <p> If {@code name} denotes a primitive type or void, an attempt
  192. * will be made to locate a user-defined class in the unnamed package whose
  193. * name is {@code name}. Therefore, this method cannot be used to
  194. * obtain any of the {@code Class} objects representing primitive
  195. * types or void.
  196. *
  197. * <p> If {@code name} denotes an array class, the component type of
  198. * the array class is loaded but not initialized.
  199. *
  200. * <p> For example, in an instance method the expression:
  201. *
  202. * <blockquote>
  203. * {@code Class.forName("Foo")}
  204. * </blockquote>
  205. *
  206. * is equivalent to:
  207. *
  208. * <blockquote>
  209. * {@code Class.forName("Foo", true, this.getClass().getClassLoader())}
  210. * </blockquote>
  211. *
  212. * Note that this method throws errors related to loading, linking or
  213. * initializing as specified in Sections 12.2, 12.3 and 12.4 of <em>The
  214. * Java Language Specification</em>.
  215. * Note that this method does not check whether the requested class
  216. * is accessible to its caller.
  217. *
  218. * <p> If the {@code loader} is {@code null}, and a security
  219. * manager is present, and the caller's class loader is not null, then this
  220. * method calls the security manager's {@code checkPermission} method
  221. * with a {@code RuntimePermission("getClassLoader")} permission to
  222. * ensure it's ok to access the bootstrap class loader.
  223. *
  224. * @param name fully qualified name of the desired class
  225. * @param initialize whether the class must be initialized
  226. * @param loader class loader from which the class must be loaded
  227. * @return class object representing the desired class
  228. *
  229. * @exception LinkageError if the linkage fails
  230. * @exception ExceptionInInitializerError if the initialization provoked
  231. * by this method fails
  232. * @exception ClassNotFoundException if the class cannot be located by
  233. * the specified class loader
  234. *
  235. * @see java.lang.Class#forName(String)
  236. * @see java.lang.ClassLoader
  237. * @since 1.2
  238. */
  239. public static Class<?> forName(String name, boolean initialize,
  240. ClassLoader loader)
  241. throws ClassNotFoundException
  242. {
  243. if (loader == null) {
  244. SecurityManager sm = System.getSecurityManager();
  245. if (sm != null) {
  246. ClassLoader ccl = ClassLoader.getCallerClassLoader();
  247. if (ccl != null) {
  248. sm.checkPermission(
  249. SecurityConstants.GET_CLASSLOADER_PERMISSION);
  250. }
  251. }
  252. }
  253. return forName0(name, initialize, loader);
  254. }
  255. /** Called after security checks have been made. */
  256. private static native Class<?> forName0(String name, boolean initialize,
  257. ClassLoader loader)
  258. throws ClassNotFoundException;
  259. /**
  260. * Creates a new instance of the class represented by this {@code Class}
  261. * object. The class is instantiated as if by a {@code new}
  262. * expression with an empty argument list. The class is initialized if it
  263. * has not already been initialized.
  264. *
  265. * <p>Note that this method propagates any exception thrown by the
  266. * nullary constructor, including a checked exception. Use of
  267. * this method effectively bypasses the compile-time exception
  268. * checking that would otherwise be performed by the compiler.
  269. * The {@link
  270. * java.lang.reflect.Constructor#newInstance(java.lang.Object...)
  271. * Constructor.newInstance} method avoids this problem by wrapping
  272. * any exception thrown by the constructor in a (checked) {@link
  273. * java.lang.reflect.InvocationTargetException}.
  274. *
  275. * @return a newly allocated instance of the class represented by this
  276. * object.
  277. * @exception IllegalAccessException if the class or its nullary
  278. * constructor is not accessible.
  279. * @exception InstantiationException
  280. * if this {@code Class} represents an abstract class,
  281. * an interface, an array class, a primitive type, or void;
  282. * or if the class has no nullary constructor;
  283. * or if the instantiation fails for some other reason.
  284. * @exception ExceptionInInitializerError if the initialization
  285. * provoked by this method fails.
  286. * @exception SecurityException
  287. * If a security manager, <i>s</i>, is present and any of the
  288. * following conditions is met:
  289. *
  290. * <ul>
  291. *
  292. * <li> invocation of
  293. * {@link SecurityManager#checkMemberAccess
  294. * s.checkMemberAccess(this, Member.PUBLIC)} denies
  295. * creation of new instances of this class
  296. *
  297. * <li> the caller's class loader is not the same as or an
  298. * ancestor of the class loader for the current class and
  299. * invocation of {@link SecurityManager#checkPackageAccess
  300. * s.checkPackageAccess()} denies access to the package
  301. * of this class
  302. *
  303. * </ul>
  304. *
  305. */
  306. public T newInstance()
  307. throws InstantiationException, IllegalAccessException
  308. {
  309. if (System.getSecurityManager() != null) {
  310. checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader());
  311. }
  312. return newInstance0();
  313. }
  314. private T newInstance0()
  315. throws InstantiationException, IllegalAccessException
  316. {
  317. // NOTE: the following code may not be strictly correct under
  318. // the current Java memory model.
  319. // Constructor lookup
  320. if (cachedConstructor == null) {
  321. if (this == Class.class) {
  322. throw new IllegalAccessException(
  323. "Can not call newInstance() on the Class for java.lang.Class"
  324. );
  325. }
  326. try {
  327. Class<?>[] empty = {};
  328. final Constructor<T> c = getConstructor0(empty, Member.DECLARED);
  329. // Disable accessibility checks on the constructor
  330. // since we have to do the security check here anyway
  331. // (the stack depth is wrong for the Constructor's
  332. // security check to work)
  333. java.security.AccessController.doPrivileged(
  334. new java.security.PrivilegedAction<Void>() {
  335. public Void run() {
  336. c.setAccessible(true);
  337. return null;
  338. }
  339. });
  340. cachedConstructor = c;
  341. } catch (NoSuchMethodException e) {
  342. throw new InstantiationException(getName());
  343. }
  344. }
  345. Constructor<T> tmpConstructor = cachedConstructor;
  346. // Security check (same as in java.lang.reflect.Constructor)
  347. int modifiers = tmpConstructor.getModifiers();
  348. if (!Reflection.quickCheckMemberAccess(this, modifiers)) {
  349. Class<?> caller = Reflection.getCallerClass(3);
  350. if (newInstanceCallerCache != caller) {
  351. Reflection.ensureMemberAccess(caller, this, null, modifiers);
  352. newInstanceCallerCache = caller;
  353. }
  354. }
  355. // Run constructor
  356. try {
  357. return tmpConstructor.newInstance((Object[])null);
  358. } catch (InvocationTargetException e) {
  359. Unsafe.getUnsafe().throwException(e.getTargetException());
  360. // Not reached
  361. return null;
  362. }
  363. }
  364. private volatile transient Constructor<T> cachedConstructor;
  365. private volatile transient Class<?> newInstanceCallerCache;
  366. /**
  367. * Determines if the specified {@code Object} is assignment-compatible
  368. * with the object represented by this {@code Class}. This method is
  369. * the dynamic equivalent of the Java language {@code instanceof}
  370. * operator. The method returns {@code true} if the specified
  371. * {@code Object} argument is non-null and can be cast to the
  372. * reference type represented by this {@code Class} object without
  373. * raising a {@code ClassCastException.} It returns {@code false}
  374. * otherwise.
  375. *
  376. * <p> Specifically, if this {@code Class} object represents a
  377. * declared class, this method returns {@code true} if the specified
  378. * {@code Object} argument is an instance of the represented class (or
  379. * of any of its subclasses); it returns {@code false} otherwise. If
  380. * this {@code Class} object represents an array class, this method
  381. * returns {@code true} if the specified {@code Object} argument
  382. * can be converted to an object of the array class by an identity
  383. * conversion or by a widening reference conversion; it returns
  384. * {@code false} otherwise. If this {@code Class} object
  385. * represents an interface, this method returns {@code true} if the
  386. * class or any superclass of the specified {@code Object} argument
  387. * implements this interface; it returns {@code false} otherwise. If
  388. * this {@code Class} object represents a primitive type, this method
  389. * returns {@code false}.
  390. *
  391. * @param obj the object to check
  392. * @return true if {@code obj} is an instance of this class
  393. *
  394. * @since JDK1.1
  395. */
  396. public native boolean isInstance(Object obj);
  397. /**
  398. * Determines if the class or interface represented by this
  399. * {@code Class} object is either the same as, or is a superclass or
  400. * superinterface of, the class or interface represented by the specified
  401. * {@code Class} parameter. It returns {@code true} if so;
  402. * otherwise it returns {@code false}. If this {@code Class}
  403. * object represents a primitive type, this method returns
  404. * {@code true} if the specified {@code Class} parameter is
  405. * exactly this {@code Class} object; otherwise it returns
  406. * {@code false}.
  407. *
  408. * <p> Specifically, this method tests whether the type represented by the
  409. * specified {@code Class} parameter can be converted to the type
  410. * represented by this {@code Class} object via an identity conversion
  411. * or via a widening reference conversion. See <em>The Java Language
  412. * Specification</em>, sections 5.1.1 and 5.1.4 , for details.
  413. *
  414. * @param cls the {@code Class} object to be checked
  415. * @return the {@code boolean} value indicating whether objects of the
  416. * type {@code cls} can be assigned to objects of this class
  417. * @exception NullPointerException if the specified Class parameter is
  418. * null.
  419. * @since JDK1.1
  420. */
  421. public native boolean isAssignableFrom(Class<?> cls);
  422. /**
  423. * Determines if the specified {@code Class} object represents an
  424. * interface type.
  425. *
  426. * @return {@code true} if this object represents an interface;
  427. * {@code false} otherwise.
  428. */
  429. public native boolean isInterface();
  430. /**
  431. * Determines if this {@code Class} object represents an array class.
  432. *
  433. * @return {@code true} if this object represents an array class;
  434. * {@code false} otherwise.
  435. * @since JDK1.1
  436. */
  437. public native boolean isArray();
  438. /**
  439. * Determines if the specified {@code Class} object represents a
  440. * primitive type.
  441. *
  442. * <p> There are nine predefined {@code Class} objects to represent
  443. * the eight primitive types and void. These are created by the Java
  444. * Virtual Machine, and have the same names as the primitive types that
  445. * they represent, namely {@code boolean}, {@code byte},
  446. * {@code char}, {@code short}, {@code int},
  447. * {@code long}, {@code float}, and {@code double}.
  448. *
  449. * <p> These objects may only be accessed via the following public static
  450. * final variables, and are the only {@code Class} objects for which
  451. * this method returns {@code true}.
  452. *
  453. * @return true if and only if this class represents a primitive type
  454. *
  455. * @see java.lang.Boolean#TYPE
  456. * @see java.lang.Character#TYPE
  457. * @see java.lang.Byte#TYPE
  458. * @see java.lang.Short#TYPE
  459. * @see java.lang.Integer#TYPE
  460. * @see java.lang.Long#TYPE
  461. * @see java.lang.Float#TYPE
  462. * @see java.lang.Double#TYPE
  463. * @see java.lang.Void#TYPE
  464. * @since JDK1.1
  465. */
  466. public native boolean isPrimitive();
  467. /**
  468. * Returns true if this {@code Class} object represents an annotation
  469. * type. Note that if this method returns true, {@link #isInterface()}
  470. * would also return true, as all annotation types are also interfaces.
  471. *
  472. * @return {@code true} if this class object represents an annotation
  473. * type; {@code false} otherwise
  474. * @since 1.5
  475. */
  476. public boolean isAnnotation() {
  477. return (getModifiers() & ANNOTATION) != 0;
  478. }
  479. /**
  480. * Returns {@code true} if this class is a synthetic class;
  481. * returns {@code false} otherwise.
  482. * @return {@code true} if and only if this class is a synthetic class as
  483. * defined by the Java Language Specification.
  484. * @since 1.5
  485. */
  486. public boolean isSynthetic() {
  487. return (getModifiers() & SYNTHETIC) != 0;
  488. }
  489. /**
  490. * Returns the name of the entity (class, interface, array class,
  491. * primitive type, or void) represented by this {@code Class} object,
  492. * as a {@code String}.
  493. *
  494. * <p> If this class object represents a reference type that is not an
  495. * array type then the binary name of the class is returned, as specified
  496. * by
  497. * <cite>The Java&trade; Language Specification</cite>.
  498. *
  499. * <p> If this class object represents a primitive type or void, then the
  500. * name returned is a {@code String} equal to the Java language
  501. * keyword corresponding to the primitive type or void.
  502. *
  503. * <p> If this class object represents a class of arrays, then the internal
  504. * form of the name consists of the name of the element type preceded by
  505. * one or more '{@code [}' characters representing the depth of the array
  506. * nesting. The encoding of element type names is as follows:
  507. *
  508. * <blockquote><table summary="Element types and encodings">
  509. * <tr><th> Element Type <th> &nbsp;&nbsp;&nbsp; <th> Encoding
  510. * <tr><td> boolean <td> &nbsp;&nbsp;&nbsp; <td align=center> Z
  511. * <tr><td> byte <td> &nbsp;&nbsp;&nbsp; <td align=center> B
  512. * <tr><td> char <td> &nbsp;&nbsp;&nbsp; <td align=center> C
  513. * <tr><td> class or interface
  514. * <td> &nbsp;&nbsp;&nbsp; <td align=center> L<i>classname</i>;
  515. * <tr><td> double <td> &nbsp;&nbsp;&nbsp; <td align=center> D
  516. * <tr><td> float <td> &nbsp;&nbsp;&nbsp; <td align=center> F
  517. * <tr><td> int <td> &nbsp;&nbsp;&nbsp; <td align=center> I
  518. * <tr><td> long <td> &nbsp;&nbsp;&nbsp; <td align=center> J
  519. * <tr><td> short <td> &nbsp;&nbsp;&nbsp; <td align=center> S
  520. * </table></blockquote>
  521. *
  522. * <p> The class or interface name <i>classname</i> is the binary name of
  523. * the class specified above.
  524. *
  525. * <p> Examples:
  526. * <blockquote><pre>
  527. * String.class.getName()
  528. * returns "java.lang.String"
  529. * byte.class.getName()
  530. * returns "byte"
  531. * (new Object[3]).getClass().getName()
  532. * returns "[Ljava.lang.Object;"
  533. * (new int[3][4][5][6][7][8][9]).getClass().getName()
  534. * returns "[[[[[[[I"
  535. * </pre></blockquote>
  536. *
  537. * @return the name of the class or interface
  538. * represented by this object.
  539. */
  540. public String getName() {
  541. String name = this.name;
  542. if (name == null)
  543. this.name = name = getName0();
  544. return name;
  545. }
  546. // cache the name to reduce the number of calls into the VM
  547. private transient String name;
  548. private native String getName0();
  549. /**
  550. * Returns the class loader for the class. Some implementations may use
  551. * null to represent the bootstrap class loader. This method will return
  552. * null in such implementations if this class was loaded by the bootstrap
  553. * class loader.
  554. *
  555. * <p> If a security manager is present, and the caller's class loader is
  556. * not null and the caller's class loader is not the same as or an ancestor of
  557. * the class loader for the class whose class loader is requested, then
  558. * this method calls the security manager's {@code checkPermission}
  559. * method with a {@code RuntimePermission("getClassLoader")}
  560. * permission to ensure it's ok to access the class loader for the class.
  561. *
  562. * <p>If this object
  563. * represents a primitive type or void, null is returned.
  564. *
  565. * @return the class loader that loaded the class or interface
  566. * represented by this object.
  567. * @throws SecurityException
  568. * if a security manager exists and its
  569. * {@code checkPermission} method denies
  570. * access to the class loader for the class.
  571. * @see java.lang.ClassLoader
  572. * @see SecurityManager#checkPermission
  573. * @see java.lang.RuntimePermission
  574. */
  575. public ClassLoader getClassLoader() {
  576. ClassLoader cl = getClassLoader0();
  577. if (cl == null)
  578. return null;
  579. SecurityManager sm = System.getSecurityManager();
  580. if (sm != null) {
  581. ClassLoader ccl = ClassLoader.getCallerClassLoader();
  582. if (ccl != null && ccl != cl && !cl.isAncestor(ccl)) {
  583. sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
  584. }
  585. }
  586. return cl;
  587. }
  588. // Package-private to allow ClassLoader access
  589. native ClassLoader getClassLoader0();
  590. /**
  591. * Returns an array of {@code TypeVariable} objects that represent the
  592. * type variables declared by the generic declaration represented by this
  593. * {@code GenericDeclaration} object, in declaration order. Returns an
  594. * array of length 0 if the underlying generic declaration declares no type
  595. * variables.
  596. *
  597. * @return an array of {@code TypeVariable} objects that represent
  598. * the type variables declared by this generic declaration
  599. * @throws java.lang.reflect.GenericSignatureFormatError if the generic
  600. * signature of this generic declaration does not conform to
  601. * the format specified in
  602. * <cite>The Java&trade; Virtual Machine Specification</cite>
  603. * @since 1.5
  604. */
  605. public TypeVariable<Class<T>>[] getTypeParameters() {
  606. if (getGenericSignature() != null)
  607. return (TypeVariable<Class<T>>[])getGenericInfo().getTypeParameters();
  608. else
  609. return (TypeVariable<Class<T>>[])new TypeVariable<?>[0];
  610. }
  611. /**
  612. * Returns the {@code Class} representing the superclass of the entity
  613. * (class, interface, primitive type or void) represented by this
  614. * {@code Class}. If this {@code Class} represents either the
  615. * {@code Object} class, an interface, a primitive type, or void, then
  616. * null is returned. If this object represents an array class then the
  617. * {@code Class} object representing the {@code Object} class is
  618. * returned.
  619. *
  620. * @return the superclass of the class represented by this object.
  621. */
  622. public native Class<? super T> getSuperclass();
  623. /**
  624. * Returns the {@code Type} representing the direct superclass of
  625. * the entity (class, interface, primitive type or void) represented by
  626. * this {@code Class}.
  627. *
  628. * <p>If the superclass is a parameterized type, the {@code Type}
  629. * object returned must accurately reflect the actual type
  630. * parameters used in the source code. The parameterized type
  631. * representing the superclass is created if it had not been
  632. * created before. See the declaration of {@link
  633. * java.lang.reflect.ParameterizedType ParameterizedType} for the
  634. * semantics of the creation process for parameterized types. If
  635. * this {@code Class} represents either the {@code Object}
  636. * class, an interface, a primitive type, or void, then null is
  637. * returned. If this object represents an array class then the
  638. * {@code Class} object representing the {@code Object} class is
  639. * returned.
  640. *
  641. * @throws java.lang.reflect.GenericSignatureFormatError if the generic
  642. * class signature does not conform to the format specified in
  643. * <cite>The Java&trade; Virtual Machine Specification</cite>
  644. * @throws TypeNotPresentException if the generic superclass
  645. * refers to a non-existent type declaration
  646. * @throws java.lang.reflect.MalformedParameterizedTypeException if the
  647. * generic superclass refers to a parameterized type that cannot be
  648. * instantiated for any reason
  649. * @return the superclass of the class represented by this object
  650. * @since 1.5
  651. */
  652. public Type getGenericSuperclass() {
  653. if (getGenericSignature() != null) {
  654. // Historical irregularity:
  655. // Generic signature marks interfaces with superclass = Object
  656. // but this API returns null for interfaces
  657. if (isInterface())
  658. return null;
  659. return getGenericInfo().getSuperclass();
  660. } else
  661. return getSuperclass();
  662. }
  663. /**
  664. * Gets the package for this class. The class loader of this class is used
  665. * to find the package. If the class was loaded by the bootstrap class
  666. * loader the set of packages loaded from CLASSPATH is searched to find the
  667. * package of the class. Null is returned if no package object was created
  668. * by the class loader of this class.
  669. *
  670. * <p> Packages have attributes for versions and specifications only if the
  671. * information was defined in the manifests that accompany the classes, and
  672. * if the class loader created the package instance with the attributes
  673. * from the manifest.
  674. *
  675. * @return the package of the class, or null if no package
  676. * information is available from the archive or codebase.
  677. */
  678. public Package getPackage() {
  679. return Package.getPackage(this);
  680. }
  681. /**
  682. * Determines the interfaces implemented by the class or interface
  683. * represented by this object.
  684. *
  685. * <p> If this object represents a class, the return value is an array
  686. * containing objects representing all interfaces implemented by the
  687. * class. The order of the interface objects in the array corresponds to
  688. * the order of the interface names in the {@code implements} clause
  689. * of the declaration of the class represented by this object. For
  690. * example, given the declaration:
  691. * <blockquote>
  692. * {@code class Shimmer implements FloorWax, DessertTopping { ... }}
  693. * </blockquote>
  694. * suppose the value of {@code s} is an instance of
  695. * {@code Shimmer}; the value of the expression:
  696. * <blockquote>
  697. * {@code s.getClass().getInterfaces()[0]}
  698. * </blockquote>
  699. * is the {@code Class} object that represents interface
  700. * {@code FloorWax}; and the value of:
  701. * <blockquote>
  702. * {@code s.getClass().getInterfaces()[1]}
  703. * </blockquote>
  704. * is the {@code Class} object that represents interface
  705. * {@code DessertTopping}.
  706. *
  707. * <p> If this object represents an interface, the array contains objects
  708. * representing all interfaces extended by the interface. The order of the
  709. * interface objects in the array corresponds to the order of the interface
  710. * names in the {@code extends} clause of the declaration of the
  711. * interface represented by this object.
  712. *
  713. * <p> If this object represents a class or interface that implements no
  714. * interfaces, the method returns an array of length 0.
  715. *
  716. * <p> If this object represents a primitive type or void, the method
  717. * returns an array of length 0.
  718. *
  719. * @return an array of interfaces implemented by this class.
  720. */
  721. public native Class<?>[] getInterfaces();
  722. /**
  723. * Returns the {@code Type}s representing the interfaces
  724. * directly implemented by the class or interface represented by
  725. * this object.
  726. *
  727. * <p>If a superinterface is a parameterized type, the
  728. * {@code Type} object returned for it must accurately reflect
  729. * the actual type parameters used in the source code. The
  730. * parameterized type representing each superinterface is created
  731. * if it had not been created before. See the declaration of
  732. * {@link java.lang.reflect.ParameterizedType ParameterizedType}
  733. * for the semantics of the creation process for parameterized
  734. * types.
  735. *
  736. * <p> If this object represents a class, the return value is an
  737. * array containing objects representing all interfaces
  738. * implemented by the class. The order of the interface objects in
  739. * the array corresponds to the order of the interface names in
  740. * the {@code implements} clause of the declaration of the class
  741. * represented by this object. In the case of an array class, the
  742. * interfaces {@code Cloneable} and {@code Serializable} are
  743. * returned in that order.
  744. *
  745. * <p>If this object represents an interface, the array contains
  746. * objects representing all interfaces directly extended by the
  747. * interface. The order of the interface objects in the array
  748. * corresponds to the order of the interface names in the
  749. * {@code extends} clause of the declaration of the interface
  750. * represented by this object.
  751. *
  752. * <p>If this object represents a class or interface that
  753. * implements no interfaces, the method returns an array of length
  754. * 0.
  755. *
  756. * <p>If this object represents a primitive type or void, the
  757. * method returns an array of length 0.
  758. *
  759. * @throws java.lang.reflect.GenericSignatureFormatError
  760. * if the generic class signature does not conform to the format
  761. * specified in
  762. * <cite>The Java&trade; Virtual Machine Specification</cite>
  763. * @throws TypeNotPresentException if any of the generic
  764. * superinterfaces refers to a non-existent type declaration
  765. * @throws java.lang.reflect.MalformedParameterizedTypeException
  766. * if any of the generic superinterfaces refer to a parameterized
  767. * type that cannot be instantiated for any reason
  768. * @return an array of interfaces implemented by this class
  769. * @since 1.5
  770. */
  771. public Type[] getGenericInterfaces() {
  772. if (getGenericSignature() != null)
  773. return getGenericInfo().getSuperInterfaces();
  774. else
  775. return getInterfaces();
  776. }
  777. /**
  778. * Returns the {@code Class} representing the component type of an
  779. * array. If this class does not represent an array class this method
  780. * returns null.
  781. *
  782. * @return the {@code Class} representing the component type of this
  783. * class if this class is an array
  784. * @see java.lang.reflect.Array
  785. * @since JDK1.1
  786. */
  787. public native Class<?> getComponentType();
  788. /**
  789. * Returns the Java language modifiers for this class or interface, encoded
  790. * in an integer. The modifiers consist of the Java Virtual Machine's
  791. * constants for {@code public}, {@code protected},
  792. * {@code private}, {@code final}, {@code static},
  793. * {@code abstract} and {@code interface}; they should be decoded
  794. * using the methods of class {@code Modifier}.
  795. *
  796. * <p> If the underlying class is an array class, then its
  797. * {@code public}, {@code private} and {@code protected}
  798. * modifiers are the same as those of its component type. If this
  799. * {@code Class} represents a primitive type or void, its
  800. * {@code public} modifier is always {@code true}, and its
  801. * {@code protected} and {@code private} modifiers are always
  802. * {@code false}. If this object represents an array class, a
  803. * primitive type or void, then its {@code final} modifier is always
  804. * {@code true} and its interface modifier is always
  805. * {@code false}. The values of its other modifiers are not determined
  806. * by this specification.
  807. *
  808. * <p> The modifier encodings are defined in <em>The Java Virtual Machine
  809. * Specification</em>, table 4.1.
  810. *
  811. * @return the {@code int} representing the modifiers for this class
  812. * @see java.lang.reflect.Modifier
  813. * @since JDK1.1
  814. */
  815. public native int getModifiers();
  816. /**
  817. * Gets the signers of this class.
  818. *
  819. * @return the signers of this class, or null if there are no signers. In
  820. * particular, this method returns null if this object represents
  821. * a primitive type or void.
  822. * @since JDK1.1
  823. */
  824. public native Object[] getSigners();
  825. /**
  826. * Set the signers of this class.
  827. */
  828. native void setSigners(Object[] signers);
  829. /**
  830. * If this {@code Class} object represents a local or anonymous
  831. * class within a method, returns a {@link
  832. * java.lang.reflect.Method Method} object representing the
  833. * immediately enclosing method of the underlying class. Returns
  834. * {@code null} otherwise.
  835. *
  836. * In particular, this method returns {@code null} if the underlying
  837. * class is a local or anonymous class immediately enclosed by a type
  838. * declaration, instance initializer or static initializer.
  839. *
  840. * @return the immediately enclosing method of the underlying class, if
  841. * that class is a local or anonymous class; otherwise {@code null}.
  842. * @since 1.5
  843. */
  844. public Method getEnclosingMethod() {
  845. EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
  846. if (enclosingInfo == null)
  847. return null;
  848. else {
  849. if (!enclosingInfo.isMethod())
  850. return null;
  851. MethodRepository typeInfo = MethodRepository.make(enclosingInfo.getDescriptor(),
  852. getFactory());
  853. Class<?> returnType = toClass(typeInfo.getReturnType());
  854. Type [] parameterTypes = typeInfo.getParameterTypes();
  855. Class<?>[] parameterClasses = new Class<?>[parameterTypes.length];
  856. // Convert Types to Classes; returned types *should*
  857. // be class objects since the methodDescriptor's used
  858. // don't have generics information
  859. for(int i = 0; i < parameterClasses.length; i++)
  860. parameterClasses[i] = toClass(parameterTypes[i]);
  861. /*
  862. * Loop over all declared methods; match method name,
  863. * number of and type of parameters, *and* return
  864. * type. Matching return type is also necessary
  865. * because of covariant returns, etc.
  866. */
  867. for(Method m: enclosingInfo.getEnclosingClass().getDeclaredMethods()) {
  868. if (m.getName().equals(enclosingInfo.getName()) ) {
  869. Class<?>[] candidateParamClasses = m.getParameterTypes();
  870. if (candidateParamClasses.length == parameterClasses.length) {
  871. boolean matches = true;
  872. for(int i = 0; i < candidateParamClasses.length; i++) {
  873. if (!candidateParamClasses[i].equals(parameterClasses[i])) {
  874. matches = false;
  875. break;
  876. }
  877. }
  878. if (matches) { // finally, check return type
  879. if (m.getReturnType().equals(returnType) )
  880. return m;
  881. }
  882. }
  883. }
  884. }
  885. throw new InternalError("Enclosing method not found");
  886. }
  887. }
  888. private native Object[] getEnclosingMethod0();
  889. private EnclosingMethodInfo getEnclosingMethodInfo() {
  890. Object[] enclosingInfo = getEnclosingMethod0();
  891. if (enclosingInfo == null)
  892. return null;
  893. else {
  894. return new EnclosingMethodInfo(enclosingInfo);
  895. }
  896. }
  897. private final static class EnclosingMethodInfo {
  898. private Class<?> enclosingClass;
  899. private String name;
  900. private String descriptor;
  901. private EnclosingMethodInfo(Object[] enclosingInfo) {
  902. if (enclosingInfo.length != 3)
  903. throw new InternalError("Malformed enclosing method information");
  904. try {
  905. // The array is expected to have three elements:
  906. // the immediately enclosing class
  907. enclosingClass = (Class<?>) enclosingInfo[0];
  908. assert(enclosingClass != null);
  909. // the immediately enclosing method or constructor's
  910. // name (can be null).
  911. name = (String) enclosingInfo[1];
  912. // the immediately enclosing method or constructor's
  913. // descriptor (null iff name is).
  914. descriptor = (String) enclosingInfo[2];
  915. assert((name != null && descriptor != null) || name == descriptor);
  916. } catch (ClassCastException cce) {
  917. throw new InternalError("Invalid type in enclosing method information");
  918. }
  919. }
  920. boolean isPartial() {
  921. return enclosingClass == null || name == null || descriptor == null;
  922. }
  923. boolean isConstructor() { return !isPartial() && "<init>".equals(name); }
  924. boolean isMethod() { return !isPartial() && !isConstructor() && !"<clinit>".equals(name); }
  925. Class<?> getEnclosingClass() { return enclosingClass; }
  926. String getName() { return name; }
  927. String getDescriptor() { return descriptor; }
  928. }
  929. private static Class<?> toClass(Type o) {
  930. if (o instanceof GenericArrayType)
  931. return Array.newInstance(toClass(((GenericArrayType)o).getGenericComponentType()),
  932. 0)
  933. .getClass();
  934. return (Class<?>)o;
  935. }
  936. /**
  937. * If this {@code Class} object represents a local or anonymous
  938. * class within a constructor, returns a {@link
  939. * java.lang.reflect.Constructor Constructor} object representing
  940. * the immediately enclosing constructor of the underlying
  941. * class. Returns {@code null} otherwise. In particular, this
  942. * method returns {@code null} if the underlying class is a local
  943. * or anonymous class immediately enclosed by a type declaration,
  944. * instance initializer or static initializer.
  945. *
  946. * @return the immediately enclosing constructor of the underlying class, if
  947. * that class is a local or anonymous class; otherwise {@code null}.
  948. * @since 1.5
  949. */
  950. public Constructor<?> getEnclosingConstructor() {
  951. EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
  952. if (enclosingInfo == null)
  953. return null;
  954. else {
  955. if (!enclosingInfo.isConstructor())
  956. return null;
  957. ConstructorRepository typeInfo = ConstructorRepository.make(enclosingInfo.getDescriptor(),
  958. getFactory());
  959. Type [] parameterTypes = typeInfo.getParameterTypes();
  960. Class<?>[] parameterClasses = new Class<?>[parameterTypes.length];
  961. // Convert Types to Classes; returned types *should*
  962. // be class objects since the methodDescriptor's used
  963. // don't have generics information
  964. for(int i = 0; i < parameterClasses.length; i++)
  965. parameterClasses[i] = toClass(parameterTypes[i]);
  966. /*
  967. * Loop over all declared constructors; match number
  968. * of and type of parameters.
  969. */
  970. for(Constructor<?> c: enclosingInfo.getEnclosingClass().getDeclaredConstructors()) {
  971. Class<?>[] candidateParamClasses = c.getParameterTypes();
  972. if (candidateParamClasses.length == parameterClasses.length) {
  973. boolean matches = true;
  974. for(int i = 0; i < candidateParamClasses.length; i++) {
  975. if (!candidateParamClasses[i].equals(parameterClasses[i])) {
  976. matches = false;
  977. break;
  978. }
  979. }
  980. if (matches)
  981. return c;
  982. }
  983. }
  984. throw new InternalError("Enclosing constructor not found");
  985. }
  986. }
  987. /**
  988. * If the class or interface represented by this {@code Class} object
  989. * is a member of another class, returns the {@code Class} object
  990. * representing the class in which it was declared. This method returns
  991. * null if this class or interface is not a member of any other class. If
  992. * this {@code Class} object represents an array class, a primitive
  993. * type, or void,then this method returns null.
  994. *
  995. * @return the declaring class for this class
  996. * @since JDK1.1
  997. */
  998. public native Class<?> getDeclaringClass();
  999. /**
  1000. * Returns the immediately enclosing class of the underlying
  1001. * class. If the underlying class is a top level class this
  1002. * method returns {@code null}.
  1003. * @return the immediately enclosing class of the underlying class
  1004. * @since 1.5
  1005. */
  1006. public Class<?> getEnclosingClass() {
  1007. // There are five kinds of classes (or interfaces):
  1008. // a) Top level classes
  1009. // b) Nested classes (static member classes)
  1010. // c) Inner classes (non-static member classes)
  1011. // d) Local classes (named classes declared within a method)
  1012. // e) Anonymous classes
  1013. // JVM Spec 4.8.6: A class must have an EnclosingMethod
  1014. // attribute if and only if it is a local class or an
  1015. // anonymous class.
  1016. EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
  1017. if (enclosingInfo == null) {
  1018. // This is a top level or a nested class or an inner class (a, b, or c)
  1019. return getDeclaringClass();
  1020. } else {
  1021. Class<?> enclosingClass = enclosingInfo.getEnclosingClass();
  1022. // This is a local class or an anonymous class (d or e)
  1023. if (enclosingClass == this || enclosingClass == null)
  1024. throw new InternalError("Malformed enclosing method information");
  1025. else
  1026. return enclosingClass;
  1027. }
  1028. }
  1029. /**
  1030. * Returns the simple name of the underlying class as given in the
  1031. * source code. Returns an empty string if the underlying class is
  1032. * anonymous.
  1033. *
  1034. * <p>The simple name of an array is the simple name of the
  1035. * component type with "[]" appended. In particular the simple
  1036. * name of an array whose component type is anonymous is "[]".
  1037. *
  1038. * @return the simple name of the underlying class
  1039. * @since 1.5
  1040. */
  1041. public String getSimpleName() {
  1042. if (isArray())
  1043. return getComponentType().getSimpleName()+"[]";
  1044. String simpleName = getSimpleBinaryName();
  1045. if (simpleName == null) { // top level class
  1046. simpleName = getName();
  1047. return simpleName.substring(simpleName.lastIndexOf(".")+1); // strip the package name
  1048. }
  1049. // According to JLS3 "Binary Compatibility" (13.1) the binary
  1050. // name of non-package classes (not top level) is the binary
  1051. // name of the immediately enclosing class followed by a '$' followed by:
  1052. // (for nested and inner classes): the simple name.
  1053. // (for local classes): 1 or more digits followed by the simple name.
  1054. // (for anonymous classes): 1 or more digits.
  1055. // Since getSimpleBinaryName() will strip the binary name of
  1056. // the immediatly enclosing class, we are now looking at a
  1057. // string that matches the regular expression "\$[0-9]*"
  1058. // followed by a simple name (considering the simple of an
  1059. // anonymous class to be the empty string).
  1060. // Remove leading "\$[0-9]*" from the name
  1061. int length = simpleName.length();
  1062. if (length < 1 || simpleName.charAt(0) != '$')
  1063. throw new InternalError("Malformed class name");
  1064. int index = 1;
  1065. while (index < length && isAsciiDigit(simpleName.charAt(index)))
  1066. index++;
  1067. // Eventually, this is the empty string iff this is an anonymous class
  1068. return simpleName.substring(index);
  1069. }
  1070. /**
  1071. * Character.isDigit answers {@code true} to some non-ascii
  1072. * digits. This one does not.
  1073. */
  1074. private static boolean isAsciiDigit(char c) {
  1075. return '0' <= c && c <= '9';
  1076. }
  1077. /**
  1078. * Returns the canonical name of the underlying class as
  1079. * defined by the Java Language Specification. Returns null if
  1080. * the underlying class does not have a canonical name (i.e., if
  1081. * it is a local or anonymous class or an array whose component
  1082. * type does not have a canonical name).
  1083. * @return the canonical name of the underlying class if it exists, and
  1084. * {@code null} otherwise.
  1085. * @since 1.5
  1086. */
  1087. public String getCanonicalName() {
  1088. if (isArray()) {
  1089. String canonicalName = getComponentType().getCanonicalName();
  1090. if (canonicalName != null)
  1091. return canonicalName + "[]";
  1092. else
  1093. return null;
  1094. }
  1095. if (isLocalOrAnonymousClass())
  1096. return null;
  1097. Class<?> enclosingClass = getEnclosingClass();
  1098. if (enclosingClass == null) { // top level class
  1099. return getName();
  1100. } else {
  1101. String enclosingName = enclosingClass.getCanonicalName();
  1102. if (enclosingName == null)
  1103. return null;
  1104. return enclosingName + "." + getSimpleName();
  1105. }
  1106. }
  1107. /**
  1108. * Returns {@code true} if and only if the underlying class
  1109. * is an anonymous class.
  1110. *
  1111. * @return {@code true} if and only if this class is an anonymous class.
  1112. * @since 1.5
  1113. */
  1114. public boolean isAnonymousClass() {
  1115. return "".equals(getSimpleName());
  1116. }
  1117. /**
  1118. * Returns {@code true} if and only if the underlying class
  1119. * is a local class.
  1120. *
  1121. * @return {@code true} if and only if this class is a local class.
  1122. * @since 1.5
  1123. */
  1124. public boolean isLocalClass() {
  1125. return isLocalOrAnonymousClass() && !isAnonymousClass();
  1126. }
  1127. /**
  1128. * Returns {@code true} if and only if the underlying class
  1129. * is a member class.
  1130. *
  1131. * @return {@code true} if and only if this class is a member class.
  1132. * @since 1.5
  1133. */
  1134. public boolean isMemberClass() {
  1135. return getSimpleBinaryName() != null && !isLocalOrAnonymousClass();
  1136. }
  1137. /**
  1138. * Returns the "simple binary name" of the underlying class, i.e.,
  1139. * the binary name without the leading enclosing class name.
  1140. * Returns {@code null} if the underlying class is a top level
  1141. * class.
  1142. */
  1143. private String getSimpleBinaryName() {
  1144. Class<?> enclosingClass = getEnclosingClass();
  1145. if (enclosingClass == null) // top level class
  1146. return null;
  1147. // Otherwise, strip the enclosing class' name
  1148. try {
  1149. return getName().substring(enclosingClass.getName().length());
  1150. } catch (IndexOutOfBoundsException ex) {
  1151. throw new InternalError("Malformed class name");
  1152. }
  1153. }
  1154. /**
  1155. * Returns {@code true} if this is a local class or an anonymous
  1156. * class. Returns {@code false} otherwise.
  1157. */
  1158. private boolean isLocalOrAnonymousClass() {
  1159. // JVM Spec 4.8.6: A class must have an EnclosingMethod
  1160. // attribute if and only if it is a local class or an
  1161. // anonymous class.
  1162. return getEnclosingMethodInfo() != null;
  1163. }
  1164. /**
  1165. * Returns an array containing {@code Class} objects representing all
  1166. * the public classes and interfaces that are members of the class
  1167. * represented by this {@code Class} object. This includes public
  1168. * class and interface members inherited from superclasses and public class
  1169. * and interface members declared by the class. This method returns an
  1170. * array of length 0 if this {@code Class} object has no public member
  1171. * classes or interfaces. This method also returns an array of length 0 if
  1172. * this {@code Class} object represents a primitive type, an array
  1173. * class, or void.
  1174. *
  1175. * @return the array of {@code Class} objects representing the public
  1176. * members of this class
  1177. * @exception SecurityException
  1178. * If a security manager, <i>s</i>, is present and any of the
  1179. * following conditions is met:
  1180. *
  1181. * <ul>
  1182. *
  1183. * <li> invocation of
  1184. * {@link SecurityManager#checkMemberAccess
  1185. * s.checkMemberAccess(this, Member.PUBLIC)} method
  1186. * denies access to the classes within this class
  1187. *
  1188. * <li> the caller's class loader is not the same as or an
  1189. * ancestor of the class loader for the current class and
  1190. * invocation of {@link SecurityManager#checkPackageAccess
  1191. * s.checkPackageAccess()} denies access to the package
  1192. * of this class
  1193. *
  1194. * </ul>
  1195. *
  1196. * @since JDK1.1
  1197. */
  1198. public Class<?>[] getClasses() {
  1199. // be very careful not to change the stack depth of this
  1200. // checkMemberAccess call for security reasons
  1201. // see java.lang.SecurityManager.checkMemberAccess
  1202. checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader());
  1203. // Privileged so this implementation can look at DECLARED classes,
  1204. // something the caller might not have privilege to do. The code here
  1205. // is allowed to look at DECLARED classes because (1) it does not hand
  1206. // out anything other than public members and (2) public member access
  1207. // has already been ok'd by the SecurityManager.
  1208. return java.security.AccessController.doPrivileged(
  1209. new java.security.PrivilegedAction<Class<?>[]>() {
  1210. public Class[] run() {
  1211. List<Class<?>> list = new ArrayList<>();
  1212. Class<?> currentClass = Class.this;
  1213. while (currentClass != null) {
  1214. Class<?>[] members = currentClass.getDeclaredClasses();
  1215. for (int i = 0; i < members.length; i++) {
  1216. if (Modifier.isPublic(members[i].getModifiers())) {
  1217. list.add(members[i]);
  1218. }
  1219. }
  1220. currentClass = currentClass.getSuperclass();
  1221. }
  1222. return list.toArray(new Class[0]);
  1223. }
  1224. });
  1225. }
  1226. /**
  1227. * Returns an array containing {@code Field} objects reflecting all
  1228. * the accessible public fields of the class or interface represented by
  1229. * this {@code Class} object. The elements in the array returned are
  1230. * not sorted and are not in any particular order. This method returns an
  1231. * array of length 0 if the class or interface has no accessible public
  1232. * fields, or if it represents an array class, a primitive type, or void.
  1233. *
  1234. * <p> Specifically, if this {@code Class} object represents a class,
  1235. * this method returns the public fields of this class and of all its
  1236. * superclasses. If this {@code Class} object represents an
  1237. * interface, this method returns the fields of this interface and of all
  1238. * its superinterfaces.
  1239. *
  1240. * <p> The implicit length field for array class is not reflected by this
  1241. * method. User code should use the methods of class {@code Array} to
  1242. * manipulate arrays.
  1243. *
  1244. * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3.
  1245. *
  1246. * @return the array of {@code Field} objects representing the
  1247. * public fields
  1248. * @exception SecurityException
  1249. * If a security manager, <i>s</i>, is present and any of the
  1250. * following conditions is met:
  1251. *
  1252. * <ul>
  1253. *
  1254. * <li> invocation of
  1255. * {@link SecurityManager#checkMemberAccess
  1256. * s.checkMemberAccess(this, Member.PUBLIC)} denies
  1257. * access to the fields within this class
  1258. *
  1259. * <li> the caller's class loader is not the same as or an
  1260. * ancestor of the class loader for the current class and
  1261. * invocation of {@link SecurityManager#checkPackageAccess
  1262. * s.checkPackageAccess()} denies access to the package
  1263. * of this class
  1264. *
  1265. * </ul>
  1266. *
  1267. * @since JDK1.1
  1268. */
  1269. public Field[] getFields() throws SecurityException {
  1270. // be very careful not to change the stack depth of this
  1271. // checkMemberAccess call for security reasons
  1272. // see java.lang.SecurityManager.checkMemberAccess
  1273. checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader());
  1274. return copyFields(privateGetPublicFields(null));
  1275. }
  1276. /**
  1277. * Returns an array containing {@code Method} objects reflecting all
  1278. * the public <em>member</em> methods of the class or interface represented
  1279. * by this {@code Class} object, including those declared by the class
  1280. * or interface and those inherited from superclasses and
  1281. * superinterfaces. Array classes return all the (public) member methods
  1282. * inherited from the {@code Object} class. The elements in the array
  1283. * returned are not sorted and are not in any particular order. This
  1284. * method returns an array of length 0 if this {@code Class} object
  1285. * represents a class or interface that has no public member methods, or if
  1286. * this {@code Class} object represents a primitive type or void.
  1287. *
  1288. * <p> The class initialization method {@code <clinit>} is not
  1289. * included in the returned array. If the class declares multiple public
  1290. * member methods with the same parameter types, they are all included in
  1291. * the returned array.
  1292. *
  1293. * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.4.
  1294. *
  1295. * @return the array of {@code Method} objects representing the
  1296. * public methods of this class
  1297. * @exception SecurityException
  1298. * If a security manager, <i>s</i>, is present and any of the
  1299. * following conditions is met:
  1300. *
  1301. * <ul>
  1302. *
  1303. * <li> invocation of
  1304. * {@link SecurityManager#checkMemberAccess
  1305. * s.checkMemberAccess(this, Member.PUBLIC)} denies
  1306. * access to the methods within this class
  1307. *
  1308. * <li> the caller's class loader is not the same as or an
  1309. * ancestor of the class loader for the current class and
  1310. * invocation of {@link SecurityManager#checkPackageAccess
  1311. * s.checkPackageAccess()} denies access to the package
  1312. * of this class
  1313. *
  1314. * </ul>
  1315. *
  1316. * @since JDK1.1
  1317. */
  1318. public Method[] getMethods() throws SecurityException {
  1319. // be very careful not to change the stack depth of this
  1320. // checkMemberAccess call for security reasons
  1321. // see java.lang.SecurityManager.checkMemberAccess
  1322. checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader());
  1323. return copyMethods(privateGetPublicMethods());
  1324. }
  1325. /**
  1326. * Returns an array containing {@code Constructor} objects reflecting
  1327. * all the public constructors of the class represented by this
  1328. * {@code Class} object. An array of length 0 is returned if the
  1329. * class has no public constructors, or if the class is an array class, or
  1330. * if the class reflects a primitive type or void.
  1331. *
  1332. * Note that while this method returns an array of {@code
  1333. * Constructor<T>} objects (that is an array of constructors from
  1334. * this class), the return type of this method is {@code
  1335. * Constructor<?>[]} and <em>not</em> {@code Constructor<T>[]} as
  1336. * might be expected. This less informative return type is
  1337. * necessary since after being returned from this method, the
  1338. * array could be modified to hold {@code Constructor} objects for
  1339. * different classes, which would violate the type guarantees of
  1340. * {@code Constructor<T>[]}.
  1341. *
  1342. * @return the array of {@code Constructor} objects representing the
  1343. * public constructors of this class
  1344. * @exception SecurityException
  1345. * If a security manager, <i>s</i>, is present and any of the
  1346. * following conditions is met:
  1347. *
  1348. * <ul>
  1349. *
  1350. * <li> invocation of
  1351. * {@link SecurityManager#checkMemberAccess
  1352. * s.checkMemberAccess(this, Member.PUBLIC)} denies
  1353. * access to the constructors within this class
  1354. *
  1355. * <li> the caller's class loader is not the same as or an
  1356. * ancestor of the class loader for the current class and
  1357. * invocation of {@link SecurityManager#checkPackageAccess
  1358. * s.checkPackageAccess()} denies access to the package
  1359. * of this class
  1360. *
  1361. * </ul>
  1362. *
  1363. * @since JDK1.1
  1364. */
  1365. public Constructor<?>[] getConstructors() throws SecurityException {
  1366. // be very careful not to change the stack depth of this
  1367. // checkMemberAccess call for security reasons
  1368. // see java.lang.SecurityManager.checkMemberAccess
  1369. checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader());
  1370. return copyConstructors(privateGetDeclaredConstructors(true));
  1371. }
  1372. /**
  1373. * Returns a {@code Field} object that reflects the specified public
  1374. * member field of the class or interface represented by this
  1375. * {@code Class} object. The {@code name} parameter is a
  1376. * {@code String} specifying the simple name of the desired field.
  1377. *
  1378. * <p> The field to be reflected is determined by the algorithm that
  1379. * follows. Let C be the class represented by this object:
  1380. * <OL>
  1381. * <LI> If C declares a public field with the name specified, that is the
  1382. * field to be reflected.</LI>
  1383. * <LI> If no field was found in step 1 above, this algorithm is applied
  1384. * recursively to each direct superinterface of C. The direct
  1385. * superinterfaces are searched in the order they were declared.</LI>
  1386. * <LI> If no field was found in steps 1 and 2 above, and C has a
  1387. * superclass S, then this algorithm is invoked recursively upon S.
  1388. * If C has no superclass, then a {@code NoSuchFieldException}
  1389. * is thrown.</LI>
  1390. * </OL>
  1391. *
  1392. * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3.
  1393. *
  1394. * @param name the field name
  1395. * @return the {@code Field} object of this class specified by
  1396. * {@code name}
  1397. * @exception NoSuchFieldException if a field with the specified name is
  1398. * not found.
  1399. * @exception NullPointerException if {@code name} is {@code null}
  1400. * @exception SecurityException
  1401. * If a security manager, <i>s</i>, is present and any of the
  1402. * following conditions is met:
  1403. *
  1404. * <ul>
  1405. *
  1406. * <li> invocation of
  1407. * {@link SecurityManager#checkMemberAccess
  1408. * s.checkMemberAccess(this, Member.PUBLIC)} denies
  1409. * access to the field
  1410. *
  1411. * <li> the caller's class loader is not the same as or an
  1412. * ancestor of the class loader for the current class and
  1413. * invocation of {@link SecurityManager#checkPackageAccess
  1414. * s.checkPackageAccess()} denies access to the package
  1415. * of this class
  1416. *
  1417. * </ul>
  1418. *
  1419. * @since JDK1.1
  1420. */
  1421. public Field getField(String name)
  1422. throws NoSuchFieldException, SecurityException {
  1423. // be very careful not to change the stack depth of this
  1424. // checkMemberAccess call for security reasons
  1425. // see java.lang.SecurityManager.checkMemberAccess
  1426. checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader());
  1427. Field field = getField0(name);
  1428. if (field == null) {
  1429. throw new NoSuchFieldException(name);
  1430. }
  1431. return field;
  1432. }
  1433. /**
  1434. * Returns a {@code Method} object that reflects the specified public
  1435. * member method of the class or interface represented by this
  1436. * {@code Class} object. The {@code name} parameter is a
  1437. * {@code String} specifying the simple name of the desired method. The
  1438. * {@code parameterTypes} parameter is an array of {@code Class}
  1439. * objects that identify the method's formal parameter types, in declared
  1440. * order. If {@code parameterTypes} is {@code null}, it is
  1441. * treated as if it were an empty array.
  1442. *
  1443. * <p> If the {@code name} is "{@code <init>};"or "{@code <clinit>}" a
  1444. * {@code NoSuchMethodException} is raised. Otherwise, the method to
  1445. * be reflected is determined by the algorithm that follows. Let C be the
  1446. * class represented by this object:
  1447. * <OL>
  1448. * <LI> C is searched for any <I>matching methods</I>. If no matching
  1449. * method is found, the algorithm of step 1 is invoked recursively on
  1450. * the superclass of C.</LI>
  1451. * <LI> If no method was found in step 1 above, the superinterfaces of C
  1452. * are searched for a matching method. If any such method is found, it
  1453. * is reflected.</LI>
  1454. * </OL>
  1455. *
  1456. * To find a matching method in a class C:&nbsp; If C declares exactly one
  1457. * public method with the specified name and exactly the same formal
  1458. * parameter types, that is the method reflected. If more than one such
  1459. * method is found in C, and one of these methods has a return type that is
  1460. * more specific than any of the others, that method is reflected;
  1461. * otherwise one of the methods is chosen arbitrarily.
  1462. *
  1463. * <p>Note that there may be more than one matching method in a
  1464. * class because while the Java language forbids a class to
  1465. * declare multiple methods with the same signature but different
  1466. * return types, the Java virtual machine does not. This
  1467. * increased flexibility in the virtual machine can be used to
  1468. * implement various language features. For example, covariant
  1469. * returns can be implemented with {@linkplain
  1470. * java.lang.reflect.Method#isBridge bridge methods}; the bridge
  1471. * method and the method being overridden would have the same
  1472. * signature but different return types.
  1473. *
  1474. * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.4.
  1475. *
  1476. * @param name the name of the method
  1477. * @param parameterTypes the list of parameters
  1478. * @return the {@code Method} object that matches the specified
  1479. * {@code name} and {@code parameterTypes}
  1480. * @exception NoSuchMethodException if a matching method is not found
  1481. * or if the name is "&lt;init&gt;"or "&lt;clinit&gt;".
  1482. * @exception NullPointerException if {@code name} is {@code null}
  1483. * @exception SecurityException
  1484. * If a security manager, <i>s</i>, is present and any of the
  1485. * following conditions is met:
  1486. *
  1487. * <ul>
  1488. *
  1489. * <li> invocation of
  1490. * {@link SecurityManager#checkMemberAccess
  1491. * s.checkMemberAccess(this, Member.PUBLIC)} denies
  1492. * access to the method
  1493. *
  1494. * <li> the caller's class loader is not the same as or an
  1495. * ancestor of the class loader for the current class and
  1496. * invocation of {@link SecurityManager#checkPackageAccess
  1497. * s.checkPackageAccess()} denies access to the package
  1498. * of this class
  1499. *
  1500. * </ul>
  1501. *
  1502. * @since JDK1.1
  1503. */
  1504. public Method getMethod(String name, Class<?>... parameterTypes)
  1505. throws NoSuchMethodException, SecurityException {
  1506. // be very careful not to change the stack depth of this
  1507. // checkMemberAccess call for security reasons
  1508. // see java.lang.SecurityManager.checkMemberAccess
  1509. checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader());
  1510. Method method = getMethod0(name, parameterTypes);
  1511. if (method == null) {
  1512. throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes));
  1513. }
  1514. return method;
  1515. }
  1516. /**
  1517. * Returns a {@code Constructor} object that reflects the specified
  1518. * public constructor of the class represented by this {@code Class}
  1519. * object. The {@code parameterTypes} parameter is an array of
  1520. * {@code Class} objects that identify the constructor's formal
  1521. * parameter types, in declared order.
  1522. *
  1523. * If this {@code Class} object represents an inner class
  1524. * declared in a non-static context, the formal parameter types
  1525. * include the explicit enclosing instance as the first parameter.
  1526. *
  1527. * <p> The constructor to reflect is the public constructor of the class
  1528. * represented by this {@code Class} object whose formal parameter
  1529. * types match those specified by {@code parameterTypes}.
  1530. *
  1531. * @param parameterTypes the parameter array
  1532. * @return the {@code Constructor} object of the public constructor that
  1533. * matches the specified {@code parameterTypes}
  1534. * @exception NoSuchMethodException if a matching method is not found.
  1535. * @exception SecurityException
  1536. * If a security manager, <i>s</i>, is present and any of the
  1537. * following conditions is met:
  1538. *
  1539. * <ul>
  1540. *
  1541. * <li> invocation of
  1542. * {@link SecurityManager#checkMemberAccess
  1543. * s.checkMemberAccess(this, Member.PUBLIC)} denies
  1544. * access to the constructor
  1545. *
  1546. * <li> the caller's class loader is not the same as or an
  1547. * ancestor of the class loader for the current class and
  1548. * invocation of {@link SecurityManager#checkPackageAccess
  1549. * s.checkPackageAccess()} denies access to the package
  1550. * of this class
  1551. *
  1552. * </ul>
  1553. *
  1554. * @since JDK1.1
  1555. */
  1556. public Constructor<T> getConstructor(Class<?>... parameterTypes)
  1557. throws NoSuchMethodException, SecurityException {
  1558. // be very careful not to change the stack depth of this
  1559. // checkMemberAccess call for security reasons
  1560. // see java.lang.SecurityManager.checkMemberAccess
  1561. checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader());
  1562. return getConstructor0(parameterTypes, Member.PUBLIC);
  1563. }
  1564. /**
  1565. * Returns an array of {@code Class} objects reflecting all the
  1566. * classes and interfaces declared as members of the class represented by
  1567. * this {@code Class} object. This includes public, protected, default
  1568. * (package) access, and private classes and interfaces declared by the
  1569. * class, but excludes inherited classes and interfaces. This method
  1570. * returns an array of length 0 if the class declares no classes or
  1571. * interfaces as members, or if this {@code Class} object represents a
  1572. * primitive type, an array class, or void.
  1573. *
  1574. * @return the array of {@code Class} objects representing all the
  1575. * declared members of this class
  1576. * @exception SecurityException
  1577. * If a security manager, <i>s</i>, is present and any of the
  1578. * following conditions is met:
  1579. *
  1580. * <ul>
  1581. *
  1582. * <li> invocation of
  1583. * {@link SecurityManager#checkMemberAccess
  1584. * s.checkMemberAccess(this, Member.DECLARED)} denies
  1585. * access to the declared classes within this class
  1586. *
  1587. * <li> the caller's class loader is not the same as or an
  1588. * ancestor of the class loader for the current class and
  1589. * invocation of {@link SecurityManager#checkPackageAccess
  1590. * s.checkPackageAccess()} denies access to the package
  1591. * of this class
  1592. *
  1593. * </ul>
  1594. *
  1595. * @since JDK1.1
  1596. */
  1597. public Class<?>[] getDeclaredClasses() throws SecurityException {
  1598. // be very careful not to change the stack depth of this
  1599. // checkMemberAccess call for security reasons
  1600. // see java.lang.SecurityManager.checkMemberAccess
  1601. checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader());
  1602. return getDeclaredClasses0();
  1603. }
  1604. /**
  1605. * Returns an array of {@code Field} objects reflecting all the fields
  1606. * declared by the class or interface represented by this
  1607. * {@code Class} object. This includes public, protected, default
  1608. * (package) access, and private fields, but excludes inherited fields.
  1609. * The elements in the array returned are not sorted and are not in any
  1610. * particular order. This method returns an array of length 0 if the class
  1611. * or interface declares no fields, or if this {@code Class} object
  1612. * represents a primitive type, an array class, or void.
  1613. *
  1614. * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3.
  1615. *
  1616. * @return the array of {@code Field} objects representing all the
  1617. * declared fields of this class
  1618. * @exception SecurityException
  1619. * If a security manager, <i>s</i>, is present and any of the
  1620. * following conditions is met:
  1621. *
  1622. * <ul>
  1623. *
  1624. * <li> invocation of
  1625. * {@link SecurityManager#checkMemberAccess
  1626. * s.checkMemberAccess(this, Member.DECLARED)} denies
  1627. * access to the declared fields within this class
  1628. *
  1629. * <li> the caller's class loader is not the same as or an
  1630. * ancestor of the class loader for the current class and
  1631. * invocation of {@link SecurityManager#checkPackageAccess
  1632. * s.checkPackageAccess()} denies access to the package
  1633. * of this class
  1634. *
  1635. * </ul>
  1636. *
  1637. * @since JDK1.1
  1638. */
  1639. public Field[] getDeclaredFields() throws SecurityException {
  1640. // be very careful not to change the stack depth of this
  1641. // checkMemberAccess call for security reasons
  1642. // see java.lang.SecurityManager.checkMemberAccess
  1643. checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader());
  1644. return copyFields(privateGetDeclaredFields(false));
  1645. }
  1646. /**
  1647. * Returns an array of {@code Method} objects reflecting all the
  1648. * methods declared by the class or interface represented by this
  1649. * {@code Class} object. This includes public, protected, default
  1650. * (package) access, and private methods, but excludes inherited methods.
  1651. * The elements in the array returned are not sorted and are not in any
  1652. * particular order. This method returns an array of length 0 if the class
  1653. * or interface declares no methods, or if this {@code Class} object
  1654. * represents a primitive type, an array class, or void. The class
  1655. * initialization method {@code <clinit>} is not included in the
  1656. * returned array. If the class declares multiple public member methods
  1657. * with the same parameter types, they are all included in the returned
  1658. * array.
  1659. *
  1660. * <p> See <em>The Java Language Specification</em>, section 8.2.
  1661. *
  1662. * @return the array of {@code Method} objects representing all the
  1663. * declared methods of this class
  1664. * @exception SecurityException
  1665. * If a security manager, <i>s</i>, is present and any of the
  1666. * following conditions is met:
  1667. *
  1668. * <ul>
  1669. *
  1670. * <li> invocation of
  1671. * {@link SecurityManager#checkMemberAccess
  1672. * s.checkMemberAccess(this, Member.DECLARED)} denies
  1673. * access to the declared methods within this class
  1674. *
  1675. * <li> the caller's class loader is not the same as or an
  1676. * ancestor of the class loader for the current class and
  1677. * invocation of {@link SecurityManager#checkPackageAccess
  1678. * s.checkPackageAccess()} denies access to the package
  1679. * of this class
  1680. *
  1681. * </ul>
  1682. *
  1683. * @since JDK1.1
  1684. */
  1685. public Method[] getDeclaredMethods() throws SecurityException {
  1686. // be very careful not to change the stack depth of this
  1687. // checkMemberAccess call for security reasons
  1688. // see java.lang.SecurityManager.checkMemberAccess
  1689. checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader());
  1690. return copyMethods(privateGetDeclaredMethods(false));
  1691. }
  1692. /**
  1693. * Returns an array of {@code Constructor} objects reflecting all the
  1694. * constructors declared by the class represented by this
  1695. * {@code Class} object. These are public, protected, default
  1696. * (package) access, and private constructors. The elements in the array
  1697. * returned are not sorted and are not in any particular order. If the
  1698. * class has a default constructor, it is included in the returned array.
  1699. * This method returns an array of length 0 if this {@code Class}
  1700. * object represents an interface, a primitive type, an array class, or
  1701. * void.
  1702. *
  1703. * <p> See <em>The Java Language Specification</em>, section 8.2.
  1704. *
  1705. * @return the array of {@code Constructor} objects representing all the
  1706. * declared constructors of this class
  1707. * @exception SecurityException
  1708. * If a security manager, <i>s</i>, is present and any of the
  1709. * following conditions is met:
  1710. *
  1711. * <ul>
  1712. *
  1713. * <li> invocation of
  1714. * {@link SecurityManager#checkMemberAccess
  1715. * s.checkMemberAccess(this, Member.DECLARED)} denies
  1716. * access to the declared constructors within this class
  1717. *
  1718. * <li> the caller's class loader is not the same as or an
  1719. * ancestor of the class loader for the current class and
  1720. * invocation of {@link SecurityManager#checkPackageAccess
  1721. * s.checkPackageAccess()} denies access to the package
  1722. * of this class
  1723. *
  1724. * </ul>
  1725. *
  1726. * @since JDK1.1
  1727. */
  1728. public Constructor<?>[] getDeclaredConstructors() throws SecurityException {
  1729. // be very careful not to change the stack depth of this
  1730. // checkMemberAccess call for security reasons
  1731. // see java.lang.SecurityManager.checkMemberAccess
  1732. checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader());
  1733. return copyConstructors(privateGetDeclaredConstructors(false));
  1734. }
  1735. /**
  1736. * Returns a {@code Field} object that reflects the specified declared
  1737. * field of the class or interface represented by this {@code Class}
  1738. * object. The {@code name} parameter is a {@code String} that
  1739. * specifies the simple name of the desired field. Note that this method
  1740. * will not reflect the {@code length} field of an array class.
  1741. *
  1742. * @param name the name of the field
  1743. * @return the {@code Field} object for the specified field in this
  1744. * class
  1745. * @exception NoSuchFieldException if a field with the specified name is
  1746. * not found.
  1747. * @exception NullPointerException if {@code name} is {@code null}
  1748. * @exception SecurityException
  1749. * If a security manager, <i>s</i>, is present and any of the
  1750. * following conditions is met:
  1751. *
  1752. * <ul>
  1753. *
  1754. * <li> invocation of
  1755. * {@link SecurityManager#checkMemberAccess
  1756. * s.checkMemberAccess(this, Member.DECLARED)} denies
  1757. * access to the declared field
  1758. *
  1759. * <li> the caller's class loader is not the same as or an
  1760. * ancestor of the class loader for the current class and
  1761. * invocation of {@link SecurityManager#checkPackageAccess
  1762. * s.checkPackageAccess()} denies access to the package
  1763. * of this class
  1764. *
  1765. * </ul>
  1766. *
  1767. * @since JDK1.1
  1768. */
  1769. public Field getDeclaredField(String name)
  1770. throws NoSuchFieldException, SecurityException {
  1771. // be very careful not to change the stack depth of this
  1772. // checkMemberAccess call for security reasons
  1773. // see java.lang.SecurityManager.checkMemberAccess
  1774. checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader());
  1775. Field field = searchFields(privateGetDeclaredFields(false), name);
  1776. if (field == null) {
  1777. throw new NoSuchFieldException(name);
  1778. }
  1779. return field;
  1780. }
  1781. /**
  1782. * Returns a {@code Method} object that reflects the specified
  1783. * declared method of the class or interface represented by this
  1784. * {@code Class} object. The {@code name} parameter is a
  1785. * {@code String} that specifies the simple name of the desired
  1786. * method, and the {@code parameterTypes} parameter is an array of
  1787. * {@code Class} objects that identify the method's formal parameter
  1788. * types, in declared order. If more than one method with the same
  1789. * parameter types is declared in a class, and one of these methods has a
  1790. * return type that is more specific than any of the others, that method is
  1791. * returned; otherwise one of the methods is chosen arbitrarily. If the
  1792. * name is "&lt;init&gt;"or "&lt;clinit&gt;" a {@code NoSuchMethodException}
  1793. * is raised.
  1794. *
  1795. * @param name the name of the method
  1796. * @param parameterTypes the parameter array
  1797. * @return the {@code Method} object for the method of this class
  1798. * matching the specified name and parameters
  1799. * @exception NoSuchMethodException if a matching method is not found.
  1800. * @exception NullPointerException if {@code name} is {@code null}
  1801. * @exception SecurityException
  1802. * If a security manager, <i>s</i>, is present and any of the
  1803. * following conditions is met:
  1804. *
  1805. * <ul>
  1806. *
  1807. * <li> invocation of
  1808. * {@link SecurityManager#checkMemberAccess
  1809. * s.checkMemberAccess(this, Member.DECLARED)} denies
  1810. * access to the declared method
  1811. *
  1812. * <li> the caller's class loader is not the same as or an
  1813. * ancestor of the class loader for the current class and
  1814. * invocation of {@link SecurityManager#checkPackageAccess
  1815. * s.checkPackageAccess()} denies access to the package
  1816. * of this class
  1817. *
  1818. * </ul>
  1819. *
  1820. * @since JDK1.1
  1821. */
  1822. public Method getDeclaredMethod(String name, Class<?>... parameterTypes)
  1823. throws NoSuchMethodException, SecurityException {
  1824. // be very careful not to change the stack depth of this
  1825. // checkMemberAccess call for security reasons
  1826. // see java.lang.SecurityManager.checkMemberAccess
  1827. checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader());
  1828. Method method = searchMethods(privateGetDeclaredMethods(false), name, parameterTypes);
  1829. if (method == null) {
  1830. throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes));
  1831. }
  1832. return method;
  1833. }
  1834. /**
  1835. * Returns a {@code Constructor} object that reflects the specified
  1836. * constructor of the class or interface represented by this
  1837. * {@code Class} object. The {@code parameterTypes} parameter is
  1838. * an array of {@code Class} objects that identify the constructor's
  1839. * formal parameter types, in declared order.
  1840. *
  1841. * If this {@code Class} object represents an inner class
  1842. * declared in a non-static context, the formal parameter types
  1843. * include the explicit enclosing instance as the first parameter.
  1844. *
  1845. * @param parameterTypes the parameter array
  1846. * @return The {@code Constructor} object for the constructor with the
  1847. * specified parameter list
  1848. * @exception NoSuchMethodException if a matching method is not found.
  1849. * @exception SecurityException
  1850. * If a security manager, <i>s</i>, is present and any of the
  1851. * following conditions is met:
  1852. *
  1853. * <ul>
  1854. *
  1855. * <li> invocation of
  1856. * {@link SecurityManager#checkMemberAccess
  1857. * s.checkMemberAccess(this, Member.DECLARED)} denies
  1858. * access to the declared constructor
  1859. *
  1860. * <li> the caller's class loader is not the same as or an
  1861. * ancestor of the class loader for the current class and
  1862. * invocation of {@link SecurityManager#checkPackageAccess
  1863. * s.checkPackageAccess()} denies access to the package
  1864. * of this class
  1865. *
  1866. * </ul>
  1867. *
  1868. * @since JDK1.1
  1869. */
  1870. public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)
  1871. throws NoSuchMethodException, SecurityException {
  1872. // be very careful not to change the stack depth of this
  1873. // checkMemberAccess call for security reasons
  1874. // see java.lang.SecurityManager.checkMemberAccess
  1875. checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader());
  1876. return getConstructor0(parameterTypes, Member.DECLARED);
  1877. }
  1878. /**
  1879. * Finds a resource with a given name. The rules for searching resources
  1880. * associated with a given class are implemented by the defining
  1881. * {@linkplain ClassLoader class loader} of the class. This method
  1882. * delegates to this object's class loader. If this object was loaded by
  1883. * the bootstrap class loader, the method delegates to {@link
  1884. * ClassLoader#getSystemResourceAsStream}.
  1885. *
  1886. * <p> Before delegation, an absolute resource name is constructed from the
  1887. * given resource name using this algorithm:
  1888. *
  1889. * <ul>
  1890. *
  1891. * <li> If the {@code name} begins with a {@code '/'}
  1892. * (<tt>'&#92;u002f'</tt>), then the absolute name of the resource is the
  1893. * portion of the {@code name} following the {@code '/'}.
  1894. *
  1895. * <li> Otherwise, the absolute name is of the following form:
  1896. *
  1897. * <blockquote>
  1898. * {@code modified_package_name/name}
  1899. * </blockquote>
  1900. *
  1901. * <p> Where the {@code modified_package_name} is the package name of this
  1902. * object with {@code '/'} substituted for {@code '.'}
  1903. * (<tt>'&#92;u002e'</tt>).
  1904. *
  1905. * </ul>
  1906. *
  1907. * @param name name of the desired resource
  1908. * @return A {@link java.io.InputStream} object or {@code null} if
  1909. * no resource with this name is found
  1910. * @throws NullPointerException If {@code name} is {@code null}
  1911. * @since JDK1.1
  1912. */
  1913. public InputStream getResourceAsStream(String name) {
  1914. name = resolveName(name);
  1915. ClassLoader cl = getClassLoader0();
  1916. if (cl==null) {
  1917. // A system class.
  1918. return ClassLoader.getSystemResourceAsStream(name);
  1919. }
  1920. return cl.getResourceAsStream(name);
  1921. }
  1922. /**
  1923. * Finds a resource with a given name. The rules for searching resources
  1924. * associated with a given class are implemented by the defining
  1925. * {@linkplain ClassLoader class loader} of the class. This method
  1926. * delegates to this object's class loader. If this object was loaded by
  1927. * the bootstrap class loader, the method delegates to {@link
  1928. * ClassLoader#getSystemResource}.
  1929. *
  1930. * <p> Before delegation, an absolute resource name is constructed from the
  1931. * given resource name using this algorithm:
  1932. *
  1933. * <ul>
  1934. *
  1935. * <li> If the {@code name} begins with a {@code '/'}
  1936. * (<tt>'&#92;u002f'</tt>), then the absolute name of the resource is the
  1937. * portion of the {@code name} following the {@code '/'}.
  1938. *
  1939. * <li> Otherwise, the absolute name is of the following form:
  1940. *
  1941. * <blockquote>
  1942. * {@code modified_package_name/name}
  1943. * </blockquote>
  1944. *
  1945. * <p> Where the {@code modified_package_name} is the package name of this
  1946. * object with {@code '/'} substituted for {@code '.'}
  1947. * (<tt>'&#92;u002e'</tt>).
  1948. *
  1949. * </ul>
  1950. *
  1951. * @param name name of the desired resource
  1952. * @return A {@link java.net.URL} object or {@code null} if no
  1953. * resource with this name is found
  1954. * @since JDK1.1
  1955. */
  1956. public java.net.URL getResource(String name) {
  1957. name = resolveName(name);
  1958. ClassLoader cl = getClassLoader0();
  1959. if (cl==null) {
  1960. // A system class.
  1961. return ClassLoader.getSystemResource(name);
  1962. }
  1963. return cl.getResource(name);
  1964. }
  1965. /** protection domain returned when the internal domain is null */
  1966. private static java.security.ProtectionDomain allPermDomain;
  1967. /**
  1968. * Returns the {@code ProtectionDomain} of this class. If there is a
  1969. * security manager installed, this method first calls the security
  1970. * manager's {@code checkPermission} method with a
  1971. * {@code RuntimePermission("getProtectionDomain")} permission to
  1972. * ensure it's ok to get the
  1973. * {@code ProtectionDomain}.
  1974. *
  1975. * @return the ProtectionDomain of this class
  1976. *
  1977. * @throws SecurityException
  1978. * if a security manager exists and its
  1979. * {@code checkPermission} method doesn't allow
  1980. * getting the ProtectionDomain.
  1981. *
  1982. * @see java.security.ProtectionDomain
  1983. * @see SecurityManager#checkPermission
  1984. * @see java.lang.RuntimePermission
  1985. * @since 1.2
  1986. */
  1987. public java.security.ProtectionDomain getProtectionDomain() {
  1988. SecurityManager sm = System.getSecurityManager();
  1989. if (sm != null) {
  1990. sm.checkPermission(SecurityConstants.GET_PD_PERMISSION);
  1991. }
  1992. java.security.ProtectionDomain pd = getProtectionDomain0();
  1993. if (pd == null) {
  1994. if (allPermDomain == null) {
  1995. java.security.Permissions perms =
  1996. new java.security.Permissions();
  1997. perms.add(SecurityConstants.ALL_PERMISSION);
  1998. allPermDomain =
  1999. new java.security.ProtectionDomain(null, perms);
  2000. }
  2001. pd = allPermDomain;
  2002. }
  2003. return pd;
  2004. }
  2005. /**
  2006. * Returns the ProtectionDomain of this class.
  2007. */
  2008. private native java.security.ProtectionDomain getProtectionDomain0();
  2009. /**
  2010. * Set the ProtectionDomain for this class. Called by
  2011. * ClassLoader.defineClass.
  2012. */
  2013. native void setProtectionDomain0(java.security.ProtectionDomain pd);
  2014. /*
  2015. * Return the Virtual Machine's Class object for the named
  2016. * primitive type.
  2017. */
  2018. static native Class getPrimitiveClass(String name);
  2019. /*
  2020. * Check if client is allowed to access members. If access is denied,
  2021. * throw a SecurityException.
  2022. *
  2023. * Be very careful not to change the stack depth of this checkMemberAccess
  2024. * call for security reasons.
  2025. * See java.lang.SecurityManager.checkMemberAccess.
  2026. *
  2027. * <p> Default policy: allow all clients access with normal Java access
  2028. * control.
  2029. */
  2030. private void checkMemberAccess(int which, ClassLoader ccl) {
  2031. SecurityManager s = System.getSecurityManager();
  2032. if (s != null) {
  2033. s.checkMemberAccess(this, which);
  2034. ClassLoader cl = getClassLoader0();
  2035. if ((ccl != null) && (ccl != cl) &&
  2036. ((cl == null) || !cl.isAncestor(ccl))) {
  2037. String name = this.getName();
  2038. int i = name.lastIndexOf('.');
  2039. if (i != -1) {
  2040. s.checkPackageAccess(name.substring(0, i));
  2041. }
  2042. }
  2043. }
  2044. }
  2045. /**
  2046. * Add a package name prefix if the name is not absolute Remove leading "/"
  2047. * if name is absolute
  2048. */
  2049. private String resolveName(String name) {
  2050. if (name == null) {
  2051. return name;
  2052. }
  2053. if (!name.startsWith("/")) {
  2054. Class<?> c = this;
  2055. while (c.isArray()) {
  2056. c = c.getComponentType();
  2057. }
  2058. String baseName = c.getName();
  2059. int index = baseName.lastIndexOf('.');
  2060. if (index != -1) {
  2061. name = baseName.substring(0, index).replace('.', '/')
  2062. +"/"+name;
  2063. }
  2064. } else {
  2065. name = name.substring(1);
  2066. }
  2067. return name;
  2068. }
  2069. /**
  2070. * Reflection support.
  2071. */
  2072. // Caches for certain reflective results
  2073. private static boolean useCaches = true;
  2074. private volatile transient SoftReference<Field[]> declaredFields;
  2075. private volatile transient SoftReference<Field[]> publicFields;
  2076. private volatile transient SoftReference<Method[]> declaredMethods;
  2077. private volatile transient SoftReference<Method[]> publicMethods;
  2078. private volatile transient SoftReference<Constructor<T>[]> declaredConstructors;
  2079. private volatile transient SoftReference<Constructor<T>[]> publicConstructors;
  2080. // Intermediate results for getFields and getMethods
  2081. private volatile transient SoftReference<Field[]> declaredPublicFields;
  2082. private volatile transient SoftReference<Method[]> declaredPublicMethods;
  2083. // Incremented by the VM on each call to JVM TI RedefineClasses()
  2084. // that redefines this class or a superclass.
  2085. private volatile transient int classRedefinedCount = 0;
  2086. // Value of classRedefinedCount when we last cleared the cached values
  2087. // that are sensitive to class redefinition.
  2088. private volatile transient int lastRedefinedCount = 0;
  2089. // Clears cached values that might possibly have been obsoleted by
  2090. // a class redefinition.
  2091. private void clearCachesOnClassRedefinition() {
  2092. if (lastRedefinedCount != classRedefinedCount) {
  2093. declaredFields = publicFields = declaredPublicFields = null;
  2094. declaredMethods = publicMethods = declaredPublicMethods = null;
  2095. declaredConstructors = publicConstructors = null;
  2096. annotations = declaredAnnotations = null;
  2097. // Use of "volatile" (and synchronization by caller in the case
  2098. // of annotations) ensures that no thread sees the update to
  2099. // lastRedefinedCount before seeing the caches cleared.
  2100. // We do not guard against brief windows during which multiple
  2101. // threads might redundantly work to fill an empty cache.
  2102. lastRedefinedCount = classRedefinedCount;
  2103. }
  2104. }
  2105. // Generic signature handling
  2106. private native String getGenericSignature();
  2107. // Generic info repository; lazily initialized
  2108. private transient ClassRepository genericInfo;
  2109. // accessor for factory
  2110. private GenericsFactory getFactory() {
  2111. // create scope and factory
  2112. return CoreReflectionFactory.make(this, ClassScope.make(this));
  2113. }
  2114. // accessor for generic info repository
  2115. private ClassRepository getGenericInfo() {
  2116. // lazily initialize repository if necessary
  2117. if (genericInfo == null) {
  2118. // create and cache generic info repository
  2119. genericInfo = ClassRepository.make(getGenericSignature(),
  2120. getFactory());
  2121. }
  2122. return genericInfo; //return cached repository
  2123. }
  2124. // Annotations handling
  2125. private native byte[] getRawAnnotations();
  2126. native ConstantPool getConstantPool();
  2127. //
  2128. //
  2129. // java.lang.reflect.Field handling
  2130. //
  2131. //
  2132. // Returns an array of "root" fields. These Field objects must NOT
  2133. // be propagated to the outside world, but must instead be copied
  2134. // via ReflectionFactory.copyField.
  2135. private Field[] privateGetDeclaredFields(boolean publicOnly) {
  2136. checkInitted();
  2137. Field[] res = null;
  2138. if (useCaches) {
  2139. clearCachesOnClassRedefinition();
  2140. if (publicOnly) {
  2141. if (declaredPublicFields != null) {
  2142. res = declaredPublicFields.get();
  2143. }
  2144. } else {
  2145. if (declaredFields != null) {
  2146. res = declaredFields.get();
  2147. }
  2148. }
  2149. if (res != null) return res;
  2150. }
  2151. // No cached value available; request value from VM
  2152. res = Reflection.filterFields(this, getDeclaredFields0(publicOnly));
  2153. if (useCaches) {
  2154. if (publicOnly) {
  2155. declaredPublicFields = new SoftReference<>(res);
  2156. } else {
  2157. declaredFields = new SoftReference<>(res);
  2158. }
  2159. }
  2160. return res;
  2161. }
  2162. // Returns an array of "root" fields. These Field objects must NOT
  2163. // be propagated to the outside world, but must instead be copied
  2164. // via ReflectionFactory.copyField.
  2165. private Field[] privateGetPublicFields(Set<Class<?>> traversedInterfaces) {
  2166. checkInitted();
  2167. Field[] res = null;
  2168. if (useCaches) {
  2169. clearCachesOnClassRedefinition();
  2170. if (publicFields != null) {
  2171. res = publicFields.get();
  2172. }
  2173. if (res != null) return res;
  2174. }
  2175. // No cached value available; compute value recursively.
  2176. // Traverse in correct order for getField().
  2177. List<Field> fields = new ArrayList<>();
  2178. if (traversedInterfaces == null) {
  2179. traversedInterfaces = new HashSet<>();
  2180. }
  2181. // Local fields
  2182. Field[] tmp = privateGetDeclaredFields(true);
  2183. addAll(fields, tmp);
  2184. // Direct superinterfaces, recursively
  2185. for (Class<?> c : getInterfaces()) {
  2186. if (!traversedInterfaces.contains(c)) {
  2187. traversedInterfaces.add(c);
  2188. addAll(fields, c.privateGetPublicFields(traversedInterfaces));
  2189. }
  2190. }
  2191. // Direct superclass, recursively
  2192. if (!isInterface()) {
  2193. Class<?> c = getSuperclass();
  2194. if (c != null) {
  2195. addAll(fields, c.privateGetPublicFields(traversedInterfaces));
  2196. }
  2197. }
  2198. res = new Field[fields.size()];
  2199. fields.toArray(res);
  2200. if (useCaches) {
  2201. publicFields = new SoftReference<>(res);
  2202. }
  2203. return res;
  2204. }
  2205. private static void addAll(Collection<Field> c, Field[] o) {
  2206. for (int i = 0; i < o.length; i++) {
  2207. c.add(o[i]);
  2208. }
  2209. }
  2210. //
  2211. //
  2212. // java.lang.reflect.Constructor handling
  2213. //
  2214. //
  2215. // Returns an array of "root" constructors. These Constructor
  2216. // objects must NOT be propagated to the outside world, but must
  2217. // instead be copied via ReflectionFactory.copyConstructor.
  2218. private Constructor<T>[] privateGetDeclaredConstructors(boolean publicOnly) {
  2219. checkInitted();
  2220. Constructor<T>[] res = null;
  2221. if (useCaches) {
  2222. clearCachesOnClassRedefinition();
  2223. if (publicOnly) {
  2224. if (publicConstructors != null) {
  2225. res = publicConstructors.get();
  2226. }
  2227. } else {
  2228. if (declaredConstructors != null) {
  2229. res = declaredConstructors.get();
  2230. }
  2231. }
  2232. if (res != null) return res;
  2233. }
  2234. // No cached value available; request value from VM
  2235. if (isInterface()) {
  2236. res = new Constructor[0];
  2237. } else {
  2238. res = getDeclaredConstructors0(publicOnly);
  2239. }
  2240. if (useCaches) {
  2241. if (publicOnly) {
  2242. publicConstructors = new SoftReference<>(res);
  2243. } else {
  2244. declaredConstructors = new SoftReference<>(res);
  2245. }
  2246. }
  2247. return res;
  2248. }
  2249. //
  2250. //
  2251. // java.lang.reflect.Method handling
  2252. //
  2253. //
  2254. // Returns an array of "root" methods. These Method objects must NOT
  2255. // be propagated to the outside world, but must instead be copied
  2256. // via ReflectionFactory.copyMethod.
  2257. private Method[] privateGetDeclaredMethods(boolean publicOnly) {
  2258. checkInitted();
  2259. Method[] res = null;
  2260. if (useCaches) {
  2261. clearCachesOnClassRedefinition();
  2262. if (publicOnly) {
  2263. if (declaredPublicMethods != null) {
  2264. res = declaredPublicMethods.get();
  2265. }
  2266. } else {
  2267. if (declaredMethods != null) {
  2268. res = declaredMethods.get();
  2269. }
  2270. }
  2271. if (res != null) return res;
  2272. }
  2273. // No cached value available; request value from VM
  2274. res = Reflection.filterMethods(this, getDeclaredMethods0(publicOnly));
  2275. if (useCaches) {
  2276. if (publicOnly) {
  2277. declaredPublicMethods = new SoftReference<>(res);
  2278. } else {
  2279. declaredMethods = new SoftReference<>(res);
  2280. }
  2281. }
  2282. return res;
  2283. }
  2284. static class MethodArray {
  2285. private Method[] methods;
  2286. private int length;
  2287. MethodArray() {
  2288. methods = new Method[20];
  2289. length = 0;
  2290. }
  2291. void add(Method m) {
  2292. if (length == methods.length) {
  2293. methods = Arrays.copyOf(methods, 2 * methods.length);
  2294. }
  2295. methods[length++] = m;
  2296. }
  2297. void addAll(Method[] ma) {
  2298. for (int i = 0; i < ma.length; i++) {
  2299. add(ma[i]);
  2300. }
  2301. }
  2302. void addAll(MethodArray ma) {
  2303. for (int i = 0; i < ma.length(); i++) {
  2304. add(ma.get(i));
  2305. }
  2306. }
  2307. void addIfNotPresent(Method newMethod) {
  2308. for (int i = 0; i < length; i++) {
  2309. Method m = methods[i];
  2310. if (m == newMethod || (m != null && m.equals(newMethod))) {
  2311. return;
  2312. }
  2313. }
  2314. add(newMethod);
  2315. }
  2316. void addAllIfNotPresent(MethodArray newMethods) {
  2317. for (int i = 0; i < newMethods.length(); i++) {
  2318. Method m = newMethods.get(i);
  2319. if (m != null) {
  2320. addIfNotPresent(m);
  2321. }
  2322. }
  2323. }
  2324. int length() {
  2325. return length;
  2326. }
  2327. Method get(int i) {
  2328. return methods[i];
  2329. }
  2330. void removeByNameAndSignature(Method toRemove) {
  2331. for (int i = 0; i < length; i++) {
  2332. Method m = methods[i];
  2333. if (m != null &&
  2334. m.getReturnType() == toRemove.getReturnType() &&
  2335. m.getName() == toRemove.getName() &&
  2336. arrayContentsEq(m.getParameterTypes(),
  2337. toRemove.getParameterTypes())) {
  2338. methods[i] = null;
  2339. }
  2340. }
  2341. }
  2342. void compactAndTrim() {
  2343. int newPos = 0;
  2344. // Get rid of null slots
  2345. for (int pos = 0; pos < length; pos++) {
  2346. Method m = methods[pos];
  2347. if (m != null) {
  2348. if (pos != newPos) {
  2349. methods[newPos] = m;
  2350. }
  2351. newPos++;
  2352. }
  2353. }
  2354. if (newPos != methods.length) {
  2355. methods = Arrays.copyOf(methods, newPos);
  2356. }
  2357. }
  2358. Method[] getArray() {
  2359. return methods;
  2360. }
  2361. }
  2362. // Returns an array of "root" methods. These Method objects must NOT
  2363. // be propagated to the outside world, but must instead be copied
  2364. // via ReflectionFactory.copyMethod.
  2365. private Method[] privateGetPublicMethods() {
  2366. checkInitted();
  2367. Method[] res = null;
  2368. if (useCaches) {
  2369. clearCachesOnClassRedefinition();
  2370. if (publicMethods != null) {
  2371. res = publicMethods.get();
  2372. }
  2373. if (res != null) return res;
  2374. }
  2375. // No cached value available; compute value recursively.
  2376. // Start by fetching public declared methods
  2377. MethodArray methods = new MethodArray();
  2378. {
  2379. Method[] tmp = privateGetDeclaredMethods(true);
  2380. methods.addAll(tmp);
  2381. }
  2382. // Now recur over superclass and direct superinterfaces.
  2383. // Go over superinterfaces first so we can more easily filter
  2384. // out concrete implementations inherited from superclasses at
  2385. // the end.
  2386. MethodArray inheritedMethods = new MethodArray();
  2387. Class<?>[] interfaces = getInterfaces();
  2388. for (int i = 0; i < interfaces.length; i++) {
  2389. inheritedMethods.addAll(interfaces[i].privateGetPublicMethods());
  2390. }
  2391. if (!isInterface()) {
  2392. Class<?> c = getSuperclass();
  2393. if (c != null) {
  2394. MethodArray supers = new MethodArray();
  2395. supers.addAll(c.privateGetPublicMethods());
  2396. // Filter out concrete implementations of any
  2397. // interface methods
  2398. for (int i = 0; i < supers.length(); i++) {
  2399. Method m = supers.get(i);
  2400. if (m != null && !Modifier.isAbstract(m.getModifiers())) {
  2401. inheritedMethods.removeByNameAndSignature(m);
  2402. }
  2403. }
  2404. // Insert superclass's inherited methods before
  2405. // superinterfaces' to satisfy getMethod's search
  2406. // order
  2407. supers.addAll(inheritedMethods);
  2408. inheritedMethods = supers;
  2409. }
  2410. }
  2411. // Filter out all local methods from inherited ones
  2412. for (int i = 0; i < methods.length(); i++) {
  2413. Method m = methods.get(i);
  2414. inheritedMethods.removeByNameAndSignature(m);
  2415. }
  2416. methods.addAllIfNotPresent(inheritedMethods);
  2417. methods.compactAndTrim();
  2418. res = methods.getArray();
  2419. if (useCaches) {
  2420. publicMethods = new SoftReference<>(res);
  2421. }
  2422. return res;
  2423. }
  2424. //
  2425. // Helpers for fetchers of one field, method, or constructor
  2426. //
  2427. private Field searchFields(Field[] fields, String name) {
  2428. String internedName = name.intern();
  2429. for (int i = 0; i < fields.length; i++) {
  2430. if (fields[i].getName() == internedName) {
  2431. return getReflectionFactory().copyField(fields[i]);
  2432. }
  2433. }
  2434. return null;
  2435. }
  2436. private Field getField0(String name) throws NoSuchFieldException {
  2437. // Note: the intent is that the search algorithm this routine
  2438. // uses be equivalent to the ordering imposed by
  2439. // privateGetPublicFields(). It fetches only the declared
  2440. // public fields for each class, however, to reduce the number
  2441. // of Field objects which have to be created for the common
  2442. // case where the field being requested is declared in the
  2443. // class which is being queried.
  2444. Field res = null;
  2445. // Search declared public fields
  2446. if ((res = searchFields(privateGetDeclaredFields(true), name)) != null) {
  2447. return res;
  2448. }
  2449. // Direct superinterfaces, recursively
  2450. Class<?>[] interfaces = getInterfaces();
  2451. for (int i = 0; i < interfaces.length; i++) {
  2452. Class<?> c = interfaces[i];
  2453. if ((res = c.getField0(name)) != null) {
  2454. return res;
  2455. }
  2456. }
  2457. // Direct superclass, recursively
  2458. if (!isInterface()) {
  2459. Class<?> c = getSuperclass();
  2460. if (c != null) {
  2461. if ((res = c.getField0(name)) != null) {
  2462. return res;
  2463. }
  2464. }
  2465. }
  2466. return null;
  2467. }
  2468. private static Method searchMethods(Method[] methods,
  2469. String name,
  2470. Class<?>[] parameterTypes)
  2471. {
  2472. Method res = null;
  2473. String internedName = name.intern();
  2474. for (int i = 0; i < methods.length; i++) {
  2475. Method m = methods[i];
  2476. if (m.getName() == internedName
  2477. && arrayContentsEq(parameterTypes, m.getParameterTypes())
  2478. && (res == null
  2479. || res.getReturnType().isAssignableFrom(m.getReturnType())))
  2480. res = m;
  2481. }
  2482. return (res == null ? res : getReflectionFactory().copyMethod(res));
  2483. }
  2484. private Method getMethod0(String name, Class<?>[] parameterTypes) {
  2485. // Note: the intent is that the search algorithm this routine
  2486. // uses be equivalent to the ordering imposed by
  2487. // privateGetPublicMethods(). It fetches only the declared
  2488. // public methods for each class, however, to reduce the
  2489. // number of Method objects which have to be created for the
  2490. // common case where the method being requested is declared in
  2491. // the class which is being queried.
  2492. Method res = null;
  2493. // Search declared public methods
  2494. if ((res = searchMethods(privateGetDeclaredMethods(true),
  2495. name,
  2496. parameterTypes)) != null) {
  2497. return res;
  2498. }
  2499. // Search superclass's methods
  2500. if (!isInterface()) {
  2501. Class<? super T> c = getSuperclass();
  2502. if (c != null) {
  2503. if ((res = c.getMethod0(name, parameterTypes)) != null) {
  2504. return res;
  2505. }
  2506. }
  2507. }
  2508. // Search superinterfaces' methods
  2509. Class<?>[] interfaces = getInterfaces();
  2510. for (int i = 0; i < interfaces.length; i++) {
  2511. Class<?> c = interfaces[i];
  2512. if ((res = c.getMethod0(name, parameterTypes)) != null) {
  2513. return res;
  2514. }
  2515. }
  2516. // Not found
  2517. return null;
  2518. }
  2519. private Constructor<T> getConstructor0(Class<?>[] parameterTypes,
  2520. int which) throws NoSuchMethodException
  2521. {
  2522. Constructor<T>[] constructors = privateGetDeclaredConstructors((which == Member.PUBLIC));
  2523. for (Constructor<T> constructor : constructors) {
  2524. if (arrayContentsEq(parameterTypes,
  2525. constructor.getParameterTypes())) {
  2526. return getReflectionFactory().copyConstructor(constructor);
  2527. }
  2528. }
  2529. throw new NoSuchMethodException(getName() + ".<init>" + argumentTypesToString(parameterTypes));
  2530. }
  2531. //
  2532. // Other helpers and base implementation
  2533. //
  2534. private static boolean arrayContentsEq(Object[] a1, Object[] a2) {
  2535. if (a1 == null) {
  2536. return a2 == null || a2.length == 0;
  2537. }
  2538. if (a2 == null) {
  2539. return a1.length == 0;
  2540. }
  2541. if (a1.length != a2.length) {
  2542. return false;
  2543. }
  2544. for (int i = 0; i < a1.length; i++) {
  2545. if (a1[i] != a2[i]) {
  2546. return false;
  2547. }
  2548. }
  2549. return true;
  2550. }
  2551. private static Field[] copyFields(Field[] arg) {
  2552. Field[] out = new Field[arg.length];
  2553. ReflectionFactory fact = getReflectionFactory();
  2554. for (int i = 0; i < arg.length; i++) {
  2555. out[i] = fact.copyField(arg[i]);
  2556. }
  2557. return out;
  2558. }
  2559. private static Method[] copyMethods(Method[] arg) {
  2560. Method[] out = new Method[arg.length];
  2561. ReflectionFactory fact = getReflectionFactory();
  2562. for (int i = 0; i < arg.length; i++) {
  2563. out[i] = fact.copyMethod(arg[i]);
  2564. }
  2565. return out;
  2566. }
  2567. private static <U> Constructor<U>[] copyConstructors(Constructor<U>[] arg) {
  2568. Constructor<U>[] out = arg.clone();
  2569. ReflectionFactory fact = getReflectionFactory();
  2570. for (int i = 0; i < out.length; i++) {
  2571. out[i] = fact.copyConstructor(out[i]);
  2572. }
  2573. return out;
  2574. }
  2575. private native Field[] getDeclaredFields0(boolean publicOnly);
  2576. private native Method[] getDeclaredMethods0(boolean publicOnly);
  2577. private native Constructor<T>[] getDeclaredConstructors0(boolean publicOnly);
  2578. private native Class<?>[] getDeclaredClasses0();
  2579. private static String argumentTypesToString(Class<?>[] argTypes) {
  2580. StringBuilder buf = new StringBuilder();
  2581. buf.append("(");
  2582. if (argTypes != null) {
  2583. for (int i = 0; i < argTypes.length; i++) {
  2584. if (i > 0) {
  2585. buf.append(", ");
  2586. }
  2587. Class<?> c = argTypes[i];
  2588. buf.append((c == null) ? "null" : c.getName());
  2589. }
  2590. }
  2591. buf.append(")");
  2592. return buf.toString();
  2593. }
  2594. /** use serialVersionUID from JDK 1.1 for interoperability */
  2595. private static final long serialVersionUID = 3206093459760846163L;
  2596. /**
  2597. * Class Class is special cased within the Serialization Stream Protocol.
  2598. *
  2599. * A Class instance is written initially into an ObjectOutputStream in the
  2600. * following format:
  2601. * <pre>
  2602. * {@code TC_CLASS} ClassDescriptor
  2603. * A ClassDescriptor is a special cased serialization of
  2604. * a {@code java.io.ObjectStreamClass} instance.
  2605. * </pre>
  2606. * A new handle is generated for the initial time the class descriptor
  2607. * is written into the stream. Future references to the class descriptor
  2608. * are written as references to the initial class descriptor instance.
  2609. *
  2610. * @see java.io.ObjectStreamClass
  2611. */
  2612. private static final ObjectStreamField[] serialPersistentFields =
  2613. new ObjectStreamField[0];
  2614. /**
  2615. * Returns the assertion status that would be assigned to this
  2616. * class if it were to be initialized at the time this method is invoked.
  2617. * If this class has had its assertion status set, the most recent
  2618. * setting will be returned; otherwise, if any package default assertion
  2619. * status pertains to this class, the most recent setting for the most
  2620. * specific pertinent package default assertion status is returned;
  2621. * otherwise, if this class is not a system class (i.e., it has a
  2622. * class loader) its class loader's default assertion status is returned;
  2623. * otherwise, the system class default assertion status is returned.
  2624. * <p>
  2625. * Few programmers will have any need for this method; it is provided
  2626. * for the benefit of the JRE itself. (It allows a class to determine at
  2627. * the time that it is initialized whether assertions should be enabled.)
  2628. * Note that this method is not guaranteed to return the actual
  2629. * assertion status that was (or will be) associated with the specified
  2630. * class when it was (or will be) initialized.
  2631. *
  2632. * @return the desired assertion status of the specified class.
  2633. * @see java.lang.ClassLoader#setClassAssertionStatus
  2634. * @see java.lang.ClassLoader#setPackageAssertionStatus
  2635. * @see java.lang.ClassLoader#setDefaultAssertionStatus
  2636. * @since 1.4
  2637. */
  2638. public boolean desiredAssertionStatus() {
  2639. ClassLoader loader = getClassLoader();
  2640. // If the loader is null this is a system class, so ask the VM
  2641. if (loader == null)
  2642. return desiredAssertionStatus0(this);
  2643. // If the classloader has been initialized with the assertion
  2644. // directives, ask it. Otherwise, ask the VM.
  2645. synchronized(loader.assertionLock) {
  2646. if (loader.classAssertionStatus != null) {
  2647. return loader.desiredAssertionStatus(getName());
  2648. }
  2649. }
  2650. return desiredAssertionStatus0(this);
  2651. }
  2652. // Retrieves the desired assertion status of this class from the VM
  2653. private static native boolean desiredAssertionStatus0(Class<?> clazz);
  2654. /**
  2655. * Returns true if and only if this class was declared as an enum in the
  2656. * source code.
  2657. *
  2658. * @return true if and only if this class was declared as an enum in the
  2659. * source code
  2660. * @since 1.5
  2661. */
  2662. public boolean isEnum() {
  2663. // An enum must both directly extend java.lang.Enum and have
  2664. // the ENUM bit set; classes for specialized enum constants
  2665. // don't do the former.
  2666. return (this.getModifiers() & ENUM) != 0 &&
  2667. this.getSuperclass() == java.lang.Enum.class;
  2668. }
  2669. // Fetches the factory for reflective objects
  2670. private static ReflectionFactory getReflectionFactory() {
  2671. if (reflectionFactory == null) {
  2672. reflectionFactory =
  2673. java.security.AccessController.doPrivileged
  2674. (new sun.reflect.ReflectionFactory.GetReflectionFactoryAction());
  2675. }
  2676. return reflectionFactory;
  2677. }
  2678. private static ReflectionFactory reflectionFactory;
  2679. // To be able to query system properties as soon as they're available
  2680. private static boolean initted = false;
  2681. private static void checkInitted() {
  2682. if (initted) return;
  2683. AccessController.doPrivileged(new PrivilegedAction<Void>() {
  2684. public Void run() {
  2685. // Tests to ensure the system properties table is fully
  2686. // initialized. This is needed because reflection code is
  2687. // called very early in the initialization process (before
  2688. // command-line arguments have been parsed and therefore
  2689. // these user-settable properties installed.) We assume that
  2690. // if System.out is non-null then the System class has been
  2691. // fully initialized and that the bulk of the startup code
  2692. // has been run.
  2693. if (System.out == null) {
  2694. // java.lang.System not yet fully initialized
  2695. return null;
  2696. }
  2697. String val =
  2698. System.getProperty("sun.reflect.noCaches");
  2699. if (val != null && val.equals("true")) {
  2700. useCaches = false;
  2701. }
  2702. initted = true;
  2703. return null;
  2704. }
  2705. });
  2706. }
  2707. /**
  2708. * Returns the elements of this enum class or null if this
  2709. * Class object does not represent an enum type.
  2710. *
  2711. * @return an array containing the values comprising the enum class
  2712. * represented by this Class object in the order they're
  2713. * declared, or null if this Class object does not
  2714. * represent an enum type
  2715. * @since 1.5
  2716. */
  2717. public T[] getEnumConstants() {
  2718. T[] values = getEnumConstantsShared();
  2719. return (values != null) ? values.clone() : null;
  2720. }
  2721. /**
  2722. * Returns the elements of this enum class or null if this
  2723. * Class object does not represent an enum type;
  2724. * identical to getEnumConstants except that the result is
  2725. * uncloned, cached, and shared by all callers.
  2726. */
  2727. T[] getEnumConstantsShared() {
  2728. if (enumConstants == null) {
  2729. if (!isEnum()) return null;
  2730. try {
  2731. final Method values = getMethod("values");
  2732. java.security.AccessController.doPrivileged(
  2733. new java.security.PrivilegedAction<Void>() {
  2734. public Void run() {
  2735. values.setAccessible(true);
  2736. return null;
  2737. }
  2738. });
  2739. enumConstants = (T[])values.invoke(null);
  2740. }
  2741. // These can happen when users concoct enum-like classes
  2742. // that don't comply with the enum spec.
  2743. catch (InvocationTargetException ex) { return null; }
  2744. catch (NoSuchMethodException ex) { return null; }
  2745. catch (IllegalAccessException ex) { return null; }
  2746. }
  2747. return enumConstants;
  2748. }
  2749. private volatile transient T[] enumConstants = null;
  2750. /**
  2751. * Returns a map from simple name to enum constant. This package-private
  2752. * method is used internally by Enum to implement
  2753. * public static <T extends Enum<T>> T valueOf(Class<T>, String)
  2754. * efficiently. Note that the map is returned by this method is
  2755. * created lazily on first use. Typically it won't ever get created.
  2756. */
  2757. Map<String, T> enumConstantDirectory() {
  2758. if (enumConstantDirectory == null) {
  2759. T[] universe = getEnumConstantsShared();
  2760. if (universe == null)
  2761. throw new IllegalArgumentException(
  2762. getName() + " is not an enum type");
  2763. Map<String, T> m = new HashMap<>(2 * universe.length);
  2764. for (T constant : universe)
  2765. m.put(((Enum<?>)constant).name(), constant);
  2766. enumConstantDirectory = m;
  2767. }
  2768. return enumConstantDirectory;
  2769. }
  2770. private volatile transient Map<String, T> enumConstantDirectory = null;
  2771. /**
  2772. * Casts an object to the class or interface represented
  2773. * by this {@code Class} object.
  2774. *
  2775. * @param obj the object to be cast
  2776. * @return the object after casting, or null if obj is null
  2777. *
  2778. * @throws ClassCastException if the object is not
  2779. * null and is not assignable to the type T.
  2780. *
  2781. * @since 1.5
  2782. */
  2783. public T cast(Object obj) {
  2784. if (obj != null && !isInstance(obj))
  2785. throw new ClassCastException(cannotCastMsg(obj));
  2786. return (T) obj;
  2787. }
  2788. private String cannotCastMsg(Object obj) {
  2789. return "Cannot cast " + obj.getClass().getName() + " to " + getName();
  2790. }
  2791. /**
  2792. * Casts this {@code Class} object to represent a subclass of the class
  2793. * represented by the specified class object. Checks that that the cast
  2794. * is valid, and throws a {@code ClassCastException} if it is not. If
  2795. * this method succeeds, it always returns a reference to this class object.
  2796. *
  2797. * <p>This method is useful when a client needs to "narrow" the type of
  2798. * a {@code Class} object to pass it to an API that restricts the
  2799. * {@code Class} objects that it is willing to accept. A cast would
  2800. * generate a compile-time warning, as the correctness of the cast
  2801. * could not be checked at runtime (because generic types are implemented
  2802. * by erasure).
  2803. *
  2804. * @return this {@code Class} object, cast to represent a subclass of
  2805. * the specified class object.
  2806. * @throws ClassCastException if this {@code Class} object does not
  2807. * represent a subclass of the specified class (here "subclass" includes
  2808. * the class itself).
  2809. * @since 1.5
  2810. */
  2811. public <U> Class<? extends U> asSubclass(Class<U> clazz) {
  2812. if (clazz.isAssignableFrom(this))
  2813. return (Class<? extends U>) this;
  2814. else
  2815. throw new ClassCastException(this.toString());
  2816. }
  2817. /**
  2818. * @throws NullPointerException {@inheritDoc}
  2819. * @since 1.5
  2820. */
  2821. public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {
  2822. if (annotationClass == null)
  2823. throw new NullPointerException();
  2824. initAnnotationsIfNecessary();
  2825. return (A) annotations.get(annotationClass);
  2826. }
  2827. /**
  2828. * @throws NullPointerException {@inheritDoc}
  2829. * @since 1.5
  2830. */
  2831. public boolean isAnnotationPresent(
  2832. Class<? extends Annotation> annotationClass) {
  2833. if (annotationClass == null)
  2834. throw new NullPointerException();
  2835. return getAnnotation(annotationClass) != null;
  2836. }
  2837. /**
  2838. * @since 1.5
  2839. */
  2840. public Annotation[] getAnnotations() {
  2841. initAnnotationsIfNecessary();
  2842. return AnnotationParser.toArray(annotations);
  2843. }
  2844. /**
  2845. * @since 1.5
  2846. */
  2847. public Annotation[] getDeclaredAnnotations() {
  2848. initAnnotationsIfNecessary();
  2849. return AnnotationParser.toArray(declaredAnnotations);
  2850. }
  2851. // Annotations cache
  2852. private transient Map<Class<? extends Annotation>, Annotation> annotations;
  2853. private transient Map<Class<? extends Annotation>, Annotation> declaredAnnotations;
  2854. private synchronized void initAnnotationsIfNecessary() {
  2855. clearCachesOnClassRedefinition();
  2856. if (annotations != null)
  2857. return;
  2858. declaredAnnotations = AnnotationParser.parseAnnotations(
  2859. getRawAnnotations(), getConstantPool(), this);
  2860. Class<?> superClass = getSuperclass();
  2861. if (superClass == null) {
  2862. annotations = declaredAnnotations;
  2863. } else {
  2864. annotations = new HashMap<>();
  2865. superClass.initAnnotationsIfNecessary();
  2866. for (Map.Entry<Class<? extends Annotation>, Annotation> e : superClass.annotations.entrySet()) {
  2867. Class<? extends Annotation> annotationClass = e.getKey();
  2868. if (AnnotationType.getInstance(annotationClass).isInherited())
  2869. annotations.put(annotationClass, e.getValue());
  2870. }
  2871. annotations.putAll(declaredAnnotations);
  2872. }
  2873. }
  2874. // Annotation types cache their internal (AnnotationType) form
  2875. private AnnotationType annotationType;
  2876. void setAnnotationType(AnnotationType type) {
  2877. annotationType = type;
  2878. }
  2879. AnnotationType getAnnotationType() {
  2880. return annotationType;
  2881. }
  2882. /* Backing store of user-defined values pertaining to this class.
  2883. * Maintained by the ClassValue class.
  2884. */
  2885. transient ClassValue.ClassValueMap classValueMap;
  2886. }