PageRenderTime 70ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

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

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