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