< prev index next >

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

Print this page




   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.lang;
  27 
  28 import java.lang.annotation.Annotation;


  29 import java.lang.module.ModuleReader;
  30 import java.lang.ref.SoftReference;
  31 import java.io.IOException;
  32 import java.io.InputStream;
  33 import java.io.ObjectStreamField;
  34 import java.lang.reflect.AnnotatedElement;
  35 import java.lang.reflect.AnnotatedType;
  36 import java.lang.reflect.Array;
  37 import java.lang.reflect.Constructor;
  38 import java.lang.reflect.Executable;
  39 import java.lang.reflect.Field;
  40 import java.lang.reflect.GenericArrayType;
  41 import java.lang.reflect.GenericDeclaration;
  42 import java.lang.reflect.InvocationTargetException;

  43 import java.lang.reflect.Member;
  44 import java.lang.reflect.Method;
  45 import java.lang.reflect.Modifier;
  46 import java.lang.reflect.Module;
  47 import java.lang.reflect.Proxy;
  48 import java.lang.reflect.Type;
  49 import java.lang.reflect.TypeVariable;
  50 import java.net.URL;
  51 import java.security.AccessController;
  52 import java.security.PrivilegedAction;
  53 import java.util.ArrayList;

  54 import java.util.Collection;
  55 import java.util.HashMap;
  56 import java.util.HashSet;
  57 import java.util.LinkedHashMap;
  58 import java.util.List;
  59 import java.util.Map;
  60 import java.util.Objects;

  61 import java.util.Set;
  62 import java.util.StringJoiner;

  63 
  64 import jdk.internal.HotSpotIntrinsicCandidate;
  65 import jdk.internal.loader.BootLoader;
  66 import jdk.internal.loader.BuiltinClassLoader;
  67 import jdk.internal.loader.ResourceHelper;

  68 import jdk.internal.misc.Unsafe;
  69 import jdk.internal.misc.VM;

  70 import jdk.internal.reflect.CallerSensitive;
  71 import jdk.internal.reflect.ConstantPool;
  72 import jdk.internal.reflect.Reflection;
  73 import jdk.internal.reflect.ReflectionFactory;
  74 import jdk.internal.vm.annotation.ForceInline;
  75 import sun.reflect.generics.factory.CoreReflectionFactory;
  76 import sun.reflect.generics.factory.GenericsFactory;
  77 import sun.reflect.generics.repository.ClassRepository;
  78 import sun.reflect.generics.repository.MethodRepository;
  79 import sun.reflect.generics.repository.ConstructorRepository;
  80 import sun.reflect.generics.scope.ClassScope;
  81 import sun.security.util.SecurityConstants;
  82 import sun.reflect.annotation.*;
  83 import sun.reflect.misc.ReflectUtil;
  84 
  85 /**
  86  * Instances of the class {@code Class} represent classes and
  87  * interfaces in a running Java application.  An enum is a kind of
  88  * class and an annotation is a kind of interface.  Every array also
  89  * belongs to a class that is reflected as a {@code Class} object


 507     @Deprecated(since="9")
 508     public T newInstance()
 509         throws InstantiationException, IllegalAccessException
 510     {
 511         if (System.getSecurityManager() != null) {
 512             checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), false);
 513         }
 514 
 515         // NOTE: the following code may not be strictly correct under
 516         // the current Java memory model.
 517 
 518         // Constructor lookup
 519         if (cachedConstructor == null) {
 520             if (this == Class.class) {
 521                 throw new IllegalAccessException(
 522                     "Can not call newInstance() on the Class for java.lang.Class"
 523                 );
 524             }
 525             try {
 526                 Class<?>[] empty = {};
 527                 final Constructor<T> c = getReflectionFactory().copyConstructor(
 528                     getConstructor0(empty, Member.DECLARED));
 529                 // Disable accessibility checks on the constructor
 530                 // since we have to do the security check here anyway
 531                 // (the stack depth is wrong for the Constructor's
 532                 // security check to work)
 533                 java.security.AccessController.doPrivileged(
 534                     new java.security.PrivilegedAction<>() {
 535                         public Void run() {
 536                                 c.setAccessible(true);
 537                                 return null;
 538                             }
 539                         });
 540                 cachedConstructor = c;
 541             } catch (NoSuchMethodException e) {
 542                 throw (InstantiationException)
 543                     new InstantiationException(getName()).initCause(e);
 544             }
 545         }
 546         Constructor<T> tmpConstructor = cachedConstructor;
 547         // Security check (same as in java.lang.reflect.Constructor)
 548         Class<?> caller = Reflection.getCallerClass();


1000      *
1001      * <p>If this object represents an interface, the array contains objects
1002      * representing all interfaces directly extended by the interface.  The
1003      * order of the interface objects in the array corresponds to the order of
1004      * the interface names in the {@code extends} clause of the declaration of
1005      * the interface represented by this object.
1006      *
1007      * <p>If this object represents a class or interface that implements no
1008      * interfaces, the method returns an array of length 0.
1009      *
1010      * <p>If this object represents a primitive type or void, the method
1011      * returns an array of length 0.
1012      *
1013      * <p>If this {@code Class} object represents an array type, the
1014      * interfaces {@code Cloneable} and {@code java.io.Serializable} are
1015      * returned in that order.
1016      *
1017      * @return an array of interfaces directly implemented by this class
1018      */
1019     public Class<?>[] getInterfaces() {
1020         // defensively copy before handing over to user code
1021         return getInterfaces(true);
1022     }
1023 
1024     private Class<?>[] getInterfaces(boolean cloneArray) {
1025         ReflectionData<T> rd = reflectionData();
1026         if (rd == null) {
1027             // no cloning required
1028             return getInterfaces0();
1029         } else {
1030             Class<?>[] interfaces = rd.interfaces;
1031             if (interfaces == null) {
1032                 interfaces = getInterfaces0();
1033                 rd.interfaces = interfaces;
1034             }
1035             // defensively copy if requested
1036             return cloneArray ? interfaces.clone() : interfaces;
1037         }
1038     }
1039 
1040     private native Class<?>[] getInterfaces0();
1041 
1042     /**
1043      * Returns the {@code Type}s representing the interfaces
1044      * directly implemented by the class or interface represented by
1045      * this object.
1046      *
1047      * <p>If a superinterface is a parameterized type, the
1048      * {@code Type} object returned for it must accurately reflect
1049      * the actual type parameters used in the source code. The
1050      * parameterized type representing each superinterface is created
1051      * if it had not been created before. See the declaration of
1052      * {@link java.lang.reflect.ParameterizedType ParameterizedType}
1053      * for the semantics of the creation process for parameterized
1054      * types.
1055      *
1056      * <p>If this object represents a class, the return value is an array


1748      *         s.checkPackageAccess()} denies access to the package
1749      *         of this class.
1750      *
1751      * @since 1.1
1752      * @jls 8.2 Class Members
1753      * @jls 8.3 Field Declarations
1754      */
1755     @CallerSensitive
1756     public Field[] getFields() throws SecurityException {
1757         checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
1758         return copyFields(privateGetPublicFields(null));
1759     }
1760 
1761 
1762     /**
1763      * Returns an array containing {@code Method} objects reflecting all the
1764      * public methods of the class or interface represented by this {@code
1765      * Class} object, including those declared by the class or interface and
1766      * those inherited from superclasses and superinterfaces.
1767      *









1768      * <p> If this {@code Class} object represents an array type, then the
1769      * returned array has a {@code Method} object for each of the public
1770      * methods inherited by the array type from {@code Object}. It does not
1771      * contain a {@code Method} object for {@code clone()}.
1772      *
1773      * <p> If this {@code Class} object represents an interface then the
1774      * returned array does not contain any implicitly declared methods from
1775      * {@code Object}. Therefore, if no methods are explicitly declared in
1776      * this interface or any of its superinterfaces then the returned array
1777      * has length 0. (Note that a {@code Class} object which represents a class
1778      * always has public methods, inherited from {@code Object}.)
1779      *
1780      * <p> The returned array never contains methods with names "{@code <init>}"
1781      * or "{@code <clinit>}".




1782      *
1783      * <p> The elements in the returned array are not sorted and are not in any
1784      * particular order.
1785      *
1786      * <p> Generally, the result is computed as with the following 4 step algorithm.
1787      * Let C be the class or interface represented by this {@code Class} object:
1788      * <ol>
1789      * <li> A union of methods is composed of:
1790      *   <ol type="a">
1791      *   <li> C's declared public instance and static methods as returned by
1792      *        {@link #getDeclaredMethods()} and filtered to include only public
1793      *        methods.</li>
1794      *   <li> If C is a class other than {@code Object}, then include the result
1795      *        of invoking this algorithm recursively on the superclass of C.</li>
1796      *   <li> Include the results of invoking this algorithm recursively on all
1797      *        direct superinterfaces of C, but include only instance methods.</li>
1798      *   </ol></li>
1799      * <li> Union from step 1 is partitioned into subsets of methods with same
1800      *      signature (name, parameter types) and return type.</li>
1801      * <li> Within each such subset only the most specific methods are selected.
1802      *      Let method M be a method from a set of methods with same signature
1803      *      and return type. M is most specific if there is no such method
1804      *      N != M from the same set, such that N is more specific than M.
1805      *      N is more specific than M if:
1806      *   <ol type="a">
1807      *   <li> N is declared by a class and M is declared by an interface; or</li>
1808      *   <li> N and M are both declared by classes or both by interfaces and
1809      *        N's declaring type is the same as or a subtype of M's declaring type
1810      *        (clearly, if M's and N's declaring types are the same type, then
1811      *        M and N are the same method).</li>
1812      *   </ol></li>
1813      * <li> The result of this algorithm is the union of all selected methods from
1814      *      step 3.</li>
1815      * </ol>
1816      *
1817      * @apiNote There may be more than one method with a particular name
1818      * and parameter types in a class because while the Java language forbids a
1819      * class to declare multiple methods with the same signature but different
1820      * return types, the Java virtual machine does not.  This
1821      * increased flexibility in the virtual machine can be used to
1822      * implement various language features.  For example, covariant
1823      * returns can be implemented with {@linkplain
1824      * java.lang.reflect.Method#isBridge bridge methods}; the bridge
1825      * method and the overriding method would have the same
1826      * signature but different return types.
1827      *
1828      * @return the array of {@code Method} objects representing the
1829      *         public methods of this class
1830      * @throws SecurityException
1831      *         If a security manager, <i>s</i>, is present and
1832      *         the caller's class loader is not the same as or an
1833      *         ancestor of the class loader for the current class and
1834      *         invocation of {@link SecurityManager#checkPackageAccess
1835      *         s.checkPackageAccess()} denies access to the package
1836      *         of this class.
1837      *
1838      * @jls 8.2 Class Members
1839      * @jls 8.4 Method Declarations
1840      * @since 1.1
1841      */
1842     @CallerSensitive
1843     public Method[] getMethods() throws SecurityException {
1844         checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
1845         return copyMethods(privateGetPublicMethods());
1846     }
1847 


1915      * @throws SecurityException
1916      *         If a security manager, <i>s</i>, is present and
1917      *         the caller's class loader is not the same as or an
1918      *         ancestor of the class loader for the current class and
1919      *         invocation of {@link SecurityManager#checkPackageAccess
1920      *         s.checkPackageAccess()} denies access to the package
1921      *         of this class.
1922      *
1923      * @since 1.1
1924      * @jls 8.2 Class Members
1925      * @jls 8.3 Field Declarations
1926      */
1927     @CallerSensitive
1928     public Field getField(String name)
1929         throws NoSuchFieldException, SecurityException {
1930         checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
1931         Field field = getField0(name);
1932         if (field == null) {
1933             throw new NoSuchFieldException(name);
1934         }
1935         return getReflectionFactory().copyField(field);
1936     }
1937 
1938 
1939     /**
1940      * Returns a {@code Method} object that reflects the specified public
1941      * member method of the class or interface represented by this
1942      * {@code Class} object. The {@code name} parameter is a
1943      * {@code String} specifying the simple name of the desired method. The
1944      * {@code parameterTypes} parameter is an array of {@code Class}
1945      * objects that identify the method's formal parameter types, in declared
1946      * order. If {@code parameterTypes} is {@code null}, it is
1947      * treated as if it were an empty array.
1948      *
1949      * <p> If this {@code Class} object represents an array type, then this
1950      * method finds any public method inherited by the array type from
1951      * {@code Object} except method {@code clone()}.
1952      *
1953      * <p> If this {@code Class} object represents an interface then this
1954      * method does not find any implicitly declared method from
1955      * {@code Object}. Therefore, if no methods are explicitly declared in
1956      * this interface or any of its superinterfaces, then this method does not
1957      * find any method.







1958      *
1959      * <p> This method does not find any method with name "{@code <init>}" or
1960      * "{@code <clinit>}".




1961      *
1962      * <p> Generally, the method to be reflected is determined by the 4 step
1963      * algorithm that follows.
1964      * Let C be the class or interface represented by this {@code Class} object:
1965      * <ol>
1966      * <li> A union of methods is composed of:
1967      *   <ol type="a">
1968      *   <li> C's declared public instance and static methods as returned by
1969      *        {@link #getDeclaredMethods()} and filtered to include only public
1970      *        methods that match given {@code name} and {@code parameterTypes}</li>
1971      *   <li> If C is a class other than {@code Object}, then include the result
1972      *        of invoking this algorithm recursively on the superclass of C.</li>
1973      *   <li> Include the results of invoking this algorithm recursively on all
1974      *        direct superinterfaces of C, but include only instance methods.</li>
1975      *   </ol></li>
1976      * <li> This union is partitioned into subsets of methods with same
1977      *      return type (the selection of methods from step 1 also guarantees that
1978      *      they have the same method name and parameter types).</li>
1979      * <li> Within each such subset only the most specific methods are selected.
1980      *      Let method M be a method from a set of methods with same VM
1981      *      signature (return type, name, parameter types).
1982      *      M is most specific if there is no such method N != M from the same
1983      *      set, such that N is more specific than M. N is more specific than M
1984      *      if:
1985      *   <ol type="a">
1986      *   <li> N is declared by a class and M is declared by an interface; or</li>
1987      *   <li> N and M are both declared by classes or both by interfaces and
1988      *        N's declaring type is the same as or a subtype of M's declaring type
1989      *        (clearly, if M's and N's declaring types are the same type, then
1990      *        M and N are the same method).</li>
1991      *   </ol></li>
1992      * <li> The result of this algorithm is chosen arbitrarily from the methods
1993      *      with most specific return type among all selected methods from step 3.
1994      *      Let R be a return type of a method M from the set of all selected methods
1995      *      from step 3. M is a method with most specific return type if there is
1996      *      no such method N != M from the same set, having return type S != R,
1997      *      such that S is a subtype of R as determined by
1998      *      R.class.{@link #isAssignableFrom}(S.class).
1999      * </ol>
2000      *
2001      * @apiNote There may be more than one method with matching name and
2002      * parameter types in a class because while the Java language forbids a
2003      * class to declare multiple methods with the same signature but different
2004      * return types, the Java virtual machine does not.  This
2005      * increased flexibility in the virtual machine can be used to
2006      * implement various language features.  For example, covariant
2007      * returns can be implemented with {@linkplain
2008      * java.lang.reflect.Method#isBridge bridge methods}; the bridge
2009      * method and the overriding method would have the same
2010      * signature but different return types. This method would return the
2011      * overriding method as it would have a more specific return type.






2012      *
2013      * @param name the name of the method
2014      * @param parameterTypes the list of parameters
2015      * @return the {@code Method} object that matches the specified
2016      *         {@code name} and {@code parameterTypes}
2017      * @throws NoSuchMethodException if a matching method is not found
2018      *         or if the name is "&lt;init&gt;"or "&lt;clinit&gt;".
2019      * @throws NullPointerException if {@code name} is {@code null}
2020      * @throws SecurityException
2021      *         If a security manager, <i>s</i>, is present and
2022      *         the caller's class loader is not the same as or an
2023      *         ancestor of the class loader for the current class and
2024      *         invocation of {@link SecurityManager#checkPackageAccess
2025      *         s.checkPackageAccess()} denies access to the package
2026      *         of this class.
2027      *
2028      * @jls 8.2 Class Members
2029      * @jls 8.4 Method Declarations
2030      * @since 1.1
2031      */
2032     @CallerSensitive
2033     public Method getMethod(String name, Class<?>... parameterTypes)
2034         throws NoSuchMethodException, SecurityException {
2035         checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
2036         Method method = getMethod0(name, parameterTypes);
2037         if (method == null) {
2038             throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes));
2039         }
2040         return getReflectionFactory().copyMethod(method);
2041     }
2042 
2043     /**
2044      * Returns a {@code Method} object that reflects the specified public
2045      * member method of the class or interface represented by this
2046      * {@code Class} object.
2047      *
2048      * @param name the name of the method
2049      * @param parameterTypes the list of parameters
2050      * @return the {@code Method} object that matches the specified
2051      *         {@code name} and {@code parameterTypes}; {@code null}
2052      *         if the method is not found or the name is
2053      *         "&lt;init&gt;"or "&lt;clinit&gt;".
2054      */
2055     Method getMethodOrNull(String name, Class<?>... parameterTypes) {
2056         Method method = getMethod0(name, parameterTypes);
2057         return method == null ? null : getReflectionFactory().copyMethod(method);
2058     }
2059 
2060 
2061     /**
2062      * Returns a {@code Constructor} object that reflects the specified
2063      * public constructor of the class represented by this {@code Class}
2064      * object. The {@code parameterTypes} parameter is an array of
2065      * {@code Class} objects that identify the constructor's formal
2066      * parameter types, in declared order.
2067      *
2068      * If this {@code Class} object represents an inner class
2069      * declared in a non-static context, the formal parameter types
2070      * include the explicit enclosing instance as the first parameter.
2071      *
2072      * <p> The constructor to reflect is the public constructor of the class
2073      * represented by this {@code Class} object whose formal parameter
2074      * types match those specified by {@code parameterTypes}.
2075      *
2076      * @param parameterTypes the parameter array
2077      * @return the {@code Constructor} object of the public constructor that
2078      *         matches the specified {@code parameterTypes}
2079      * @throws NoSuchMethodException if a matching method is not found.
2080      * @throws SecurityException
2081      *         If a security manager, <i>s</i>, is present and
2082      *         the caller's class loader is not the same as or an
2083      *         ancestor of the class loader for the current class and
2084      *         invocation of {@link SecurityManager#checkPackageAccess
2085      *         s.checkPackageAccess()} denies access to the package
2086      *         of this class.
2087      *
2088      * @since 1.1
2089      */
2090     @CallerSensitive
2091     public Constructor<T> getConstructor(Class<?>... parameterTypes)
2092         throws NoSuchMethodException, SecurityException {
2093         checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
2094         return getReflectionFactory().copyConstructor(
2095             getConstructor0(parameterTypes, Member.PUBLIC));
2096     }
2097 
2098 
2099     /**
2100      * Returns an array of {@code Class} objects reflecting all the
2101      * classes and interfaces declared as members of the class represented by
2102      * this {@code Class} object. This includes public, protected, default
2103      * (package) access, and private classes and interfaces declared by the
2104      * class, but excludes inherited classes and interfaces.  This method
2105      * returns an array of length 0 if the class declares no classes or
2106      * interfaces as members, or if this {@code Class} object represents a
2107      * primitive type, an array class, or void.
2108      *
2109      * @return the array of {@code Class} objects representing all the
2110      *         declared members of this class
2111      * @throws SecurityException
2112      *         If a security manager, <i>s</i>, is present and any of the
2113      *         following conditions is met:
2114      *
2115      *         <ul>


2322      *          <li> the caller's class loader is not the same as or an
2323      *          ancestor of the class loader for the current class and
2324      *          invocation of {@link SecurityManager#checkPackageAccess
2325      *          s.checkPackageAccess()} denies access to the package
2326      *          of this class
2327      *
2328      *          </ul>
2329      *
2330      * @since 1.1
2331      * @jls 8.2 Class Members
2332      * @jls 8.3 Field Declarations
2333      */
2334     @CallerSensitive
2335     public Field getDeclaredField(String name)
2336         throws NoSuchFieldException, SecurityException {
2337         checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
2338         Field field = searchFields(privateGetDeclaredFields(false), name);
2339         if (field == null) {
2340             throw new NoSuchFieldException(name);
2341         }
2342         return getReflectionFactory().copyField(field);
2343     }
2344 
2345 
2346     /**
2347      * Returns a {@code Method} object that reflects the specified
2348      * declared method of the class or interface represented by this
2349      * {@code Class} object. The {@code name} parameter is a
2350      * {@code String} that specifies the simple name of the desired
2351      * method, and the {@code parameterTypes} parameter is an array of
2352      * {@code Class} objects that identify the method's formal parameter
2353      * types, in declared order.  If more than one method with the same
2354      * parameter types is declared in a class, and one of these methods has a
2355      * return type that is more specific than any of the others, that method is
2356      * returned; otherwise one of the methods is chosen arbitrarily.  If the
2357      * name is "&lt;init&gt;"or "&lt;clinit&gt;" a {@code NoSuchMethodException}
2358      * is raised.
2359      *
2360      * <p> If this {@code Class} object represents an array type, then this
2361      * method does not find the {@code clone()} method.
2362      *


2382      *          <li> the caller's class loader is not the same as or an
2383      *          ancestor of the class loader for the current class and
2384      *          invocation of {@link SecurityManager#checkPackageAccess
2385      *          s.checkPackageAccess()} denies access to the package
2386      *          of this class
2387      *
2388      *          </ul>
2389      *
2390      * @jls 8.2 Class Members
2391      * @jls 8.4 Method Declarations
2392      * @since 1.1
2393      */
2394     @CallerSensitive
2395     public Method getDeclaredMethod(String name, Class<?>... parameterTypes)
2396         throws NoSuchMethodException, SecurityException {
2397         checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
2398         Method method = searchMethods(privateGetDeclaredMethods(false), name, parameterTypes);
2399         if (method == null) {
2400             throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes));
2401         }
2402         return getReflectionFactory().copyMethod(method);
2403     }
2404 
2405 
2406     /**
2407      * Returns a {@code Constructor} object that reflects the specified
2408      * constructor of the class or interface represented by this
2409      * {@code Class} object.  The {@code parameterTypes} parameter is
2410      * an array of {@code Class} objects that identify the constructor's
2411      * formal parameter types, in declared order.
2412      *
2413      * If this {@code Class} object represents an inner class
2414      * declared in a non-static context, the formal parameter types
2415      * include the explicit enclosing instance as the first parameter.
2416      *
2417      * @param parameterTypes the parameter array
2418      * @return  The {@code Constructor} object for the constructor with the
2419      *          specified parameter list
2420      * @throws  NoSuchMethodException if a matching method is not found.
2421      * @throws  SecurityException
2422      *          If a security manager, <i>s</i>, is present and any of the


2428      *          class loader of this class and invocation of
2429      *          {@link SecurityManager#checkPermission
2430      *          s.checkPermission} method with
2431      *          {@code RuntimePermission("accessDeclaredMembers")}
2432      *          denies access to the declared constructor
2433      *
2434      *          <li> the caller's class loader is not the same as or an
2435      *          ancestor of the class loader for the current class and
2436      *          invocation of {@link SecurityManager#checkPackageAccess
2437      *          s.checkPackageAccess()} denies access to the package
2438      *          of this class
2439      *
2440      *          </ul>
2441      *
2442      * @since 1.1
2443      */
2444     @CallerSensitive
2445     public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)
2446         throws NoSuchMethodException, SecurityException {
2447         checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
2448         return getReflectionFactory().copyConstructor(
2449             getConstructor0(parameterTypes, Member.DECLARED));
2450     }
2451 
2452     /**
2453      * Finds a resource with a given name.
2454      *
2455      * <p> If this class is in a named {@link Module Module} then this method
2456      * will attempt to find the resource in the module by means of the absolute
2457      * resource name, subject to the rules for encapsulation specified in the
2458      * {@code Module} {@link Module#getResourceAsStream getResourceAsStream}
2459      * method.
2460      *
2461      * <p> Otherwise, if this class is not in a named module then the rules for
2462      * searching resources associated with a given class are implemented by the
2463      * defining {@linkplain ClassLoader class loader} of the class.  This method
2464      * delegates to this object's class loader.  If this object was loaded by
2465      * the bootstrap class loader, the method delegates to {@link
2466      * ClassLoader#getSystemResourceAsStream}.
2467      *
2468      * <p> Before finding a resource in the caller's module or delegation to a
2469      * class loader, an absolute resource name is constructed from the given


3039     // via ReflectionFactory.copyMethod.
3040     private Method[] privateGetDeclaredMethods(boolean publicOnly) {
3041         Method[] res;
3042         ReflectionData<T> rd = reflectionData();
3043         if (rd != null) {
3044             res = publicOnly ? rd.declaredPublicMethods : rd.declaredMethods;
3045             if (res != null) return res;
3046         }
3047         // No cached value available; request value from VM
3048         res = Reflection.filterMethods(this, getDeclaredMethods0(publicOnly));
3049         if (rd != null) {
3050             if (publicOnly) {
3051                 rd.declaredPublicMethods = res;
3052             } else {
3053                 rd.declaredMethods = res;
3054             }
3055         }
3056         return res;
3057     }
3058 














































































































































































3059     // Returns an array of "root" methods. These Method objects must NOT
3060     // be propagated to the outside world, but must instead be copied
3061     // via ReflectionFactory.copyMethod.
3062     private Method[] privateGetPublicMethods() {
3063         Method[] res;
3064         ReflectionData<T> rd = reflectionData();
3065         if (rd != null) {
3066             res = rd.publicMethods;
3067             if (res != null) return res;
3068         }
3069 
3070         // No cached value available; compute value recursively.
3071         // Start by fetching public declared methods...
3072         PublicMethods pms = new PublicMethods();
3073         for (Method m : privateGetDeclaredMethods(/* publicOnly */ true)) {
3074             pms.merge(m);
3075         }
3076         // ...then recur over superclass methods...
3077         Class<?> sc = getSuperclass();
3078         if (sc != null) {
3079             for (Method m : sc.privateGetPublicMethods()) {
3080                 pms.merge(m);
3081             }
3082         }
3083         // ...and finally over direct superinterfaces.
3084         for (Class<?> intf : getInterfaces(/* cloneArray */ false)) {
3085             for (Method m : intf.privateGetPublicMethods()) {
3086                 // static interface methods are not inherited
3087                 if (!Modifier.isStatic(m.getModifiers())) {
3088                     pms.merge(m);
3089                 }
3090             }







3091         }
3092 
3093         res = pms.toArray();





























3094         if (rd != null) {
3095             rd.publicMethods = res;
3096         }
3097         return res;
3098     }
3099 
3100 
3101     //
3102     // Helpers for fetchers of one field, method, or constructor
3103     //
3104 
3105     // This method does not copy the returned Field object!
3106     private static Field searchFields(Field[] fields, String name) {

3107         for (Field field : fields) {
3108             if (field.getName().equals(name)) {
3109                 return field;
3110             }
3111         }
3112         return null;
3113     }
3114 
3115     // Returns a "root" Field object. This Field object must NOT
3116     // be propagated to the outside world, but must instead be copied
3117     // via ReflectionFactory.copyField.
3118     private Field getField0(String name) {
3119         // Note: the intent is that the search algorithm this routine
3120         // uses be equivalent to the ordering imposed by
3121         // privateGetPublicFields(). It fetches only the declared
3122         // public fields for each class, however, to reduce the number
3123         // of Field objects which have to be created for the common
3124         // case where the field being requested is declared in the
3125         // class which is being queried.
3126         Field res;
3127         // Search declared public fields
3128         if ((res = searchFields(privateGetDeclaredFields(true), name)) != null) {
3129             return res;
3130         }
3131         // Direct superinterfaces, recursively
3132         Class<?>[] interfaces = getInterfaces(/* cloneArray */ false);
3133         for (Class<?> c : interfaces) {
3134             if ((res = c.getField0(name)) != null) {
3135                 return res;
3136             }
3137         }
3138         // Direct superclass, recursively
3139         if (!isInterface()) {
3140             Class<?> c = getSuperclass();
3141             if (c != null) {
3142                 if ((res = c.getField0(name)) != null) {
3143                     return res;
3144                 }
3145             }
3146         }
3147         return null;
3148     }
3149 
3150     // This method does not copy the returned Method object!
3151     private static Method searchMethods(Method[] methods,
3152                                         String name,
3153                                         Class<?>[] parameterTypes)
3154     {
3155         ReflectionFactory fact = getReflectionFactory();
3156         Method res = null;

3157         for (Method m : methods) {
3158             if (m.getName().equals(name)
3159                 && arrayContentsEq(parameterTypes,
3160                                    fact.getExecutableSharedParameterTypes(m))
3161                 && (res == null
3162                     || (res.getReturnType() != m.getReturnType()
3163                         && res.getReturnType().isAssignableFrom(m.getReturnType()))))
3164                 res = m;
3165         }
3166         return res;

3167     }
3168 
3169     private static final Class<?>[] EMPTY_CLASS_ARRAY = new Class<?>[0];




3170 
3171     // Returns a "root" Method object. This Method object must NOT
3172     // be propagated to the outside world, but must instead be copied
3173     // via ReflectionFactory.copyMethod.
3174     private Method getMethod0(String name, Class<?>[] parameterTypes) {
3175         PublicMethods.MethodList res = getMethodsRecursive(
3176             name,
3177             parameterTypes == null ? EMPTY_CLASS_ARRAY : parameterTypes,
3178             /* includeStatic */ true);
3179         return res == null ? null : res.getMostSpecific();
3180     }
3181 
3182     // Returns a list of "root" Method objects. These Method objects must NOT
3183     // be propagated to the outside world, but must instead be copied
3184     // via ReflectionFactory.copyMethod.
3185     private PublicMethods.MethodList getMethodsRecursive(String name,
3186                                                          Class<?>[] parameterTypes,
3187                                                          boolean includeStatic) {
3188         // 1st check declared public methods
3189         Method[] methods = privateGetDeclaredMethods(/* publicOnly */ true);
3190         PublicMethods.MethodList res = PublicMethods.MethodList
3191             .filter(methods, name, parameterTypes, includeStatic);
3192         // if there is at least one match among declared methods, we need not
3193         // search any further as such match surely overrides matching methods
3194         // declared in superclass(es) or interface(s).
3195         if (res != null) {














3196             return res;
3197         }
3198 
3199         // if there was no match among declared methods,
3200         // we must consult the superclass (if any) recursively...
3201         Class<?> sc = getSuperclass();
3202         if (sc != null) {
3203             res = sc.getMethodsRecursive(name, parameterTypes, includeStatic);
3204         }
3205 
3206         // ...and coalesce the superclass methods with methods obtained
3207         // from directly implemented interfaces excluding static methods...
3208         for (Class<?> intf : getInterfaces(/* cloneArray */ false)) {
3209             res = PublicMethods.MethodList.merge(
3210                 res, intf.getMethodsRecursive(name, parameterTypes,
3211                                               /* includeStatic */ false));
3212         }
3213 
3214         return res;






3215     }
3216 
3217     // Returns a "root" Constructor object. This Constructor object must NOT
3218     // be propagated to the outside world, but must instead be copied
3219     // via ReflectionFactory.copyConstructor.
3220     private Constructor<T> getConstructor0(Class<?>[] parameterTypes,
3221                                         int which) throws NoSuchMethodException
3222     {
3223         ReflectionFactory fact = getReflectionFactory();
3224         Constructor<T>[] constructors = privateGetDeclaredConstructors((which == Member.PUBLIC));
3225         for (Constructor<T> constructor : constructors) {
3226             if (arrayContentsEq(parameterTypes,
3227                                 fact.getExecutableSharedParameterTypes(constructor))) {
3228                 return constructor;
3229             }
3230         }
3231         throw new NoSuchMethodException(getName() + ".<init>" + argumentTypesToString(parameterTypes));
3232     }
3233 
3234     //
3235     // Other helpers and base implementation
3236     //
3237 
3238     private static boolean arrayContentsEq(Object[] a1, Object[] a2) {
3239         if (a1 == null) {
3240             return a2 == null || a2.length == 0;
3241         }
3242 
3243         if (a2 == null) {
3244             return a1.length == 0;
3245         }
3246 
3247         if (a1.length != a2.length) {
3248             return false;




   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.lang;
  27 
  28 import java.lang.annotation.Annotation;
  29 import java.lang.module.ModuleDescriptor.Version;
  30 import java.lang.module.ModuleFinder;
  31 import java.lang.module.ModuleReader;
  32 import java.lang.ref.SoftReference;
  33 import java.io.IOException;
  34 import java.io.InputStream;
  35 import java.io.ObjectStreamField;
  36 import java.lang.reflect.AnnotatedElement;
  37 import java.lang.reflect.AnnotatedType;
  38 import java.lang.reflect.Array;
  39 import java.lang.reflect.Constructor;
  40 import java.lang.reflect.Executable;
  41 import java.lang.reflect.Field;
  42 import java.lang.reflect.GenericArrayType;
  43 import java.lang.reflect.GenericDeclaration;
  44 import java.lang.reflect.InvocationTargetException;
  45 import java.lang.reflect.Layer;
  46 import java.lang.reflect.Member;
  47 import java.lang.reflect.Method;
  48 import java.lang.reflect.Modifier;
  49 import java.lang.reflect.Module;
  50 import java.lang.reflect.Proxy;
  51 import java.lang.reflect.Type;
  52 import java.lang.reflect.TypeVariable;
  53 import java.net.URL;
  54 import java.security.AccessController;
  55 import java.security.PrivilegedAction;
  56 import java.util.ArrayList;
  57 import java.util.Arrays;
  58 import java.util.Collection;
  59 import java.util.HashMap;
  60 import java.util.HashSet;
  61 import java.util.LinkedHashMap;
  62 import java.util.List;
  63 import java.util.Map;
  64 import java.util.Objects;
  65 import java.util.Optional;
  66 import java.util.Set;
  67 import java.util.StringJoiner;
  68 import java.util.stream.Collectors;
  69 
  70 import jdk.internal.HotSpotIntrinsicCandidate;
  71 import jdk.internal.loader.BootLoader;
  72 import jdk.internal.loader.BuiltinClassLoader;
  73 import jdk.internal.loader.ResourceHelper;
  74 import jdk.internal.misc.SharedSecrets;
  75 import jdk.internal.misc.Unsafe;
  76 import jdk.internal.misc.VM;
  77 import jdk.internal.module.ModuleHashes;
  78 import jdk.internal.reflect.CallerSensitive;
  79 import jdk.internal.reflect.ConstantPool;
  80 import jdk.internal.reflect.Reflection;
  81 import jdk.internal.reflect.ReflectionFactory;
  82 import jdk.internal.vm.annotation.ForceInline;
  83 import sun.reflect.generics.factory.CoreReflectionFactory;
  84 import sun.reflect.generics.factory.GenericsFactory;
  85 import sun.reflect.generics.repository.ClassRepository;
  86 import sun.reflect.generics.repository.MethodRepository;
  87 import sun.reflect.generics.repository.ConstructorRepository;
  88 import sun.reflect.generics.scope.ClassScope;
  89 import sun.security.util.SecurityConstants;
  90 import sun.reflect.annotation.*;
  91 import sun.reflect.misc.ReflectUtil;
  92 
  93 /**
  94  * Instances of the class {@code Class} represent classes and
  95  * interfaces in a running Java application.  An enum is a kind of
  96  * class and an annotation is a kind of interface.  Every array also
  97  * belongs to a class that is reflected as a {@code Class} object


 515     @Deprecated(since="9")
 516     public T newInstance()
 517         throws InstantiationException, IllegalAccessException
 518     {
 519         if (System.getSecurityManager() != null) {
 520             checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), false);
 521         }
 522 
 523         // NOTE: the following code may not be strictly correct under
 524         // the current Java memory model.
 525 
 526         // Constructor lookup
 527         if (cachedConstructor == null) {
 528             if (this == Class.class) {
 529                 throw new IllegalAccessException(
 530                     "Can not call newInstance() on the Class for java.lang.Class"
 531                 );
 532             }
 533             try {
 534                 Class<?>[] empty = {};
 535                 final Constructor<T> c = getConstructor0(empty, Member.DECLARED);

 536                 // Disable accessibility checks on the constructor
 537                 // since we have to do the security check here anyway
 538                 // (the stack depth is wrong for the Constructor's
 539                 // security check to work)
 540                 java.security.AccessController.doPrivileged(
 541                     new java.security.PrivilegedAction<>() {
 542                         public Void run() {
 543                                 c.setAccessible(true);
 544                                 return null;
 545                             }
 546                         });
 547                 cachedConstructor = c;
 548             } catch (NoSuchMethodException e) {
 549                 throw (InstantiationException)
 550                     new InstantiationException(getName()).initCause(e);
 551             }
 552         }
 553         Constructor<T> tmpConstructor = cachedConstructor;
 554         // Security check (same as in java.lang.reflect.Constructor)
 555         Class<?> caller = Reflection.getCallerClass();


1007      *
1008      * <p>If this object represents an interface, the array contains objects
1009      * representing all interfaces directly extended by the interface.  The
1010      * order of the interface objects in the array corresponds to the order of
1011      * the interface names in the {@code extends} clause of the declaration of
1012      * the interface represented by this object.
1013      *
1014      * <p>If this object represents a class or interface that implements no
1015      * interfaces, the method returns an array of length 0.
1016      *
1017      * <p>If this object represents a primitive type or void, the method
1018      * returns an array of length 0.
1019      *
1020      * <p>If this {@code Class} object represents an array type, the
1021      * interfaces {@code Cloneable} and {@code java.io.Serializable} are
1022      * returned in that order.
1023      *
1024      * @return an array of interfaces directly implemented by this class
1025      */
1026     public Class<?>[] getInterfaces() {





1027         ReflectionData<T> rd = reflectionData();
1028         if (rd == null) {
1029             // no cloning required
1030             return getInterfaces0();
1031         } else {
1032             Class<?>[] interfaces = rd.interfaces;
1033             if (interfaces == null) {
1034                 interfaces = getInterfaces0();
1035                 rd.interfaces = interfaces;
1036             }
1037             // defensively copy before handing over to user code
1038             return interfaces.clone();
1039         }
1040     }
1041 
1042     private native Class<?>[] getInterfaces0();
1043 
1044     /**
1045      * Returns the {@code Type}s representing the interfaces
1046      * directly implemented by the class or interface represented by
1047      * this object.
1048      *
1049      * <p>If a superinterface is a parameterized type, the
1050      * {@code Type} object returned for it must accurately reflect
1051      * the actual type parameters used in the source code. The
1052      * parameterized type representing each superinterface is created
1053      * if it had not been created before. See the declaration of
1054      * {@link java.lang.reflect.ParameterizedType ParameterizedType}
1055      * for the semantics of the creation process for parameterized
1056      * types.
1057      *
1058      * <p>If this object represents a class, the return value is an array


1750      *         s.checkPackageAccess()} denies access to the package
1751      *         of this class.
1752      *
1753      * @since 1.1
1754      * @jls 8.2 Class Members
1755      * @jls 8.3 Field Declarations
1756      */
1757     @CallerSensitive
1758     public Field[] getFields() throws SecurityException {
1759         checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
1760         return copyFields(privateGetPublicFields(null));
1761     }
1762 
1763 
1764     /**
1765      * Returns an array containing {@code Method} objects reflecting all the
1766      * public methods of the class or interface represented by this {@code
1767      * Class} object, including those declared by the class or interface and
1768      * those inherited from superclasses and superinterfaces.
1769      *
1770      * <p> If this {@code Class} object represents a type that has multiple
1771      * public methods with the same name and parameter types, but different
1772      * return types, then the returned array has a {@code Method} object for
1773      * each such method.
1774      *
1775      * <p> If this {@code Class} object represents a type with a class
1776      * initialization method {@code <clinit>}, then the returned array does
1777      * <em>not</em> have a corresponding {@code Method} object.
1778      *
1779      * <p> If this {@code Class} object represents an array type, then the
1780      * returned array has a {@code Method} object for each of the public
1781      * methods inherited by the array type from {@code Object}. It does not
1782      * contain a {@code Method} object for {@code clone()}.
1783      *
1784      * <p> If this {@code Class} object represents an interface then the
1785      * returned array does not contain any implicitly declared methods from
1786      * {@code Object}. Therefore, if no methods are explicitly declared in
1787      * this interface or any of its superinterfaces then the returned array
1788      * has length 0. (Note that a {@code Class} object which represents a class
1789      * always has public methods, inherited from {@code Object}.)
1790      *
1791      * <p> If this {@code Class} object represents a primitive type or void,
1792      * then the returned array has length 0.
1793      *
1794      * <p> Static methods declared in superinterfaces of the class or interface
1795      * represented by this {@code Class} object are not considered members of
1796      * the class or interface.
1797      *
1798      * <p> The elements in the returned array are not sorted and are not in any
1799      * particular order.
1800      *










































1801      * @return the array of {@code Method} objects representing the
1802      *         public methods of this class
1803      * @throws SecurityException
1804      *         If a security manager, <i>s</i>, is present and
1805      *         the caller's class loader is not the same as or an
1806      *         ancestor of the class loader for the current class and
1807      *         invocation of {@link SecurityManager#checkPackageAccess
1808      *         s.checkPackageAccess()} denies access to the package
1809      *         of this class.
1810      *
1811      * @jls 8.2 Class Members
1812      * @jls 8.4 Method Declarations
1813      * @since 1.1
1814      */
1815     @CallerSensitive
1816     public Method[] getMethods() throws SecurityException {
1817         checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
1818         return copyMethods(privateGetPublicMethods());
1819     }
1820 


1888      * @throws SecurityException
1889      *         If a security manager, <i>s</i>, is present and
1890      *         the caller's class loader is not the same as or an
1891      *         ancestor of the class loader for the current class and
1892      *         invocation of {@link SecurityManager#checkPackageAccess
1893      *         s.checkPackageAccess()} denies access to the package
1894      *         of this class.
1895      *
1896      * @since 1.1
1897      * @jls 8.2 Class Members
1898      * @jls 8.3 Field Declarations
1899      */
1900     @CallerSensitive
1901     public Field getField(String name)
1902         throws NoSuchFieldException, SecurityException {
1903         checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
1904         Field field = getField0(name);
1905         if (field == null) {
1906             throw new NoSuchFieldException(name);
1907         }
1908         return field;
1909     }
1910 
1911 
1912     /**
1913      * Returns a {@code Method} object that reflects the specified public
1914      * member method of the class or interface represented by this
1915      * {@code Class} object. The {@code name} parameter is a
1916      * {@code String} specifying the simple name of the desired method. The
1917      * {@code parameterTypes} parameter is an array of {@code Class}
1918      * objects that identify the method's formal parameter types, in declared
1919      * order. If {@code parameterTypes} is {@code null}, it is
1920      * treated as if it were an empty array.
1921      *
1922      * <p> If the {@code name} is "{@code <init>}" or "{@code <clinit>}" a
1923      * {@code NoSuchMethodException} is raised. Otherwise, the method to
1924      * be reflected is determined by the algorithm that follows.  Let C be the
1925      * class or interface represented by this object:
1926      * <OL>
1927      * <LI> C is searched for a <I>matching method</I>, as defined below. If a
1928      *      matching method is found, it is reflected.</LI>
1929      * <LI> If no matching method is found by step 1 then:
1930      *   <OL TYPE="a">
1931      *   <LI> If C is a class other than {@code Object}, then this algorithm is
1932      *        invoked recursively on the superclass of C.</LI>
1933      *   <LI> If C is the class {@code Object}, or if C is an interface, then
1934      *        the superinterfaces of C (if any) are searched for a matching
1935      *        method. If any such method is found, it is reflected.</LI>
1936      *   </OL></LI>
1937      * </OL>
1938      *
1939      * <p> To find a matching method in a class or interface C:&nbsp; If C
1940      * declares exactly one public method with the specified name and exactly
1941      * the same formal parameter types, that is the method reflected. If more
1942      * than one such method is found in C, and one of these methods has a
1943      * return type that is more specific than any of the others, that method is
1944      * reflected; otherwise one of the methods is chosen arbitrarily.
1945      *
1946      * <p>Note that there may be more than one matching method in a
1947      * class because while the Java language forbids a class to
1948      * declare multiple methods with the same signature but different







































1949      * return types, the Java virtual machine does not.  This
1950      * increased flexibility in the virtual machine can be used to
1951      * implement various language features.  For example, covariant
1952      * returns can be implemented with {@linkplain
1953      * java.lang.reflect.Method#isBridge bridge methods}; the bridge
1954      * method and the method being overridden would have the same
1955      * signature but different return types.
1956      *
1957      * <p> If this {@code Class} object represents an array type, then this
1958      * method does not find the {@code clone()} method.
1959      *
1960      * <p> Static methods declared in superinterfaces of the class or interface
1961      * represented by this {@code Class} object are not considered members of
1962      * the class or interface.
1963      *
1964      * @param name the name of the method
1965      * @param parameterTypes the list of parameters
1966      * @return the {@code Method} object that matches the specified
1967      *         {@code name} and {@code parameterTypes}
1968      * @throws NoSuchMethodException if a matching method is not found
1969      *         or if the name is "&lt;init&gt;"or "&lt;clinit&gt;".
1970      * @throws NullPointerException if {@code name} is {@code null}
1971      * @throws SecurityException
1972      *         If a security manager, <i>s</i>, is present and
1973      *         the caller's class loader is not the same as or an
1974      *         ancestor of the class loader for the current class and
1975      *         invocation of {@link SecurityManager#checkPackageAccess
1976      *         s.checkPackageAccess()} denies access to the package
1977      *         of this class.
1978      *
1979      * @jls 8.2 Class Members
1980      * @jls 8.4 Method Declarations
1981      * @since 1.1
1982      */
1983     @CallerSensitive
1984     public Method getMethod(String name, Class<?>... parameterTypes)
1985         throws NoSuchMethodException, SecurityException {
1986         checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
1987         Method method = getMethod0(name, parameterTypes, true);
1988         if (method == null) {
1989             throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes));
1990         }
1991         return method;
1992     }
1993 
1994     /**
1995      * Returns a {@code Method} object that reflects the specified public
1996      * member method of the class or interface represented by this
1997      * {@code Class} object.
1998      *
1999      * @param name the name of the method
2000      * @param parameterTypes the list of parameters
2001      * @return the {@code Method} object that matches the specified
2002      *         {@code name} and {@code parameterTypes}; {@code null}
2003      *         if the method is not found or the name is
2004      *         "&lt;init&gt;"or "&lt;clinit&gt;".
2005      */
2006     Method getMethodOrNull(String name, Class<?>... parameterTypes) {
2007         return getMethod0(name, parameterTypes, true);

2008     }
2009 
2010 
2011     /**
2012      * Returns a {@code Constructor} object that reflects the specified
2013      * public constructor of the class represented by this {@code Class}
2014      * object. The {@code parameterTypes} parameter is an array of
2015      * {@code Class} objects that identify the constructor's formal
2016      * parameter types, in declared order.
2017      *
2018      * If this {@code Class} object represents an inner class
2019      * declared in a non-static context, the formal parameter types
2020      * include the explicit enclosing instance as the first parameter.
2021      *
2022      * <p> The constructor to reflect is the public constructor of the class
2023      * represented by this {@code Class} object whose formal parameter
2024      * types match those specified by {@code parameterTypes}.
2025      *
2026      * @param parameterTypes the parameter array
2027      * @return the {@code Constructor} object of the public constructor that
2028      *         matches the specified {@code parameterTypes}
2029      * @throws NoSuchMethodException if a matching method is not found.
2030      * @throws SecurityException
2031      *         If a security manager, <i>s</i>, is present and
2032      *         the caller's class loader is not the same as or an
2033      *         ancestor of the class loader for the current class and
2034      *         invocation of {@link SecurityManager#checkPackageAccess
2035      *         s.checkPackageAccess()} denies access to the package
2036      *         of this class.
2037      *
2038      * @since 1.1
2039      */
2040     @CallerSensitive
2041     public Constructor<T> getConstructor(Class<?>... parameterTypes)
2042         throws NoSuchMethodException, SecurityException {
2043         checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
2044         return getConstructor0(parameterTypes, Member.PUBLIC);

2045     }
2046 
2047 
2048     /**
2049      * Returns an array of {@code Class} objects reflecting all the
2050      * classes and interfaces declared as members of the class represented by
2051      * this {@code Class} object. This includes public, protected, default
2052      * (package) access, and private classes and interfaces declared by the
2053      * class, but excludes inherited classes and interfaces.  This method
2054      * returns an array of length 0 if the class declares no classes or
2055      * interfaces as members, or if this {@code Class} object represents a
2056      * primitive type, an array class, or void.
2057      *
2058      * @return the array of {@code Class} objects representing all the
2059      *         declared members of this class
2060      * @throws SecurityException
2061      *         If a security manager, <i>s</i>, is present and any of the
2062      *         following conditions is met:
2063      *
2064      *         <ul>


2271      *          <li> the caller's class loader is not the same as or an
2272      *          ancestor of the class loader for the current class and
2273      *          invocation of {@link SecurityManager#checkPackageAccess
2274      *          s.checkPackageAccess()} denies access to the package
2275      *          of this class
2276      *
2277      *          </ul>
2278      *
2279      * @since 1.1
2280      * @jls 8.2 Class Members
2281      * @jls 8.3 Field Declarations
2282      */
2283     @CallerSensitive
2284     public Field getDeclaredField(String name)
2285         throws NoSuchFieldException, SecurityException {
2286         checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
2287         Field field = searchFields(privateGetDeclaredFields(false), name);
2288         if (field == null) {
2289             throw new NoSuchFieldException(name);
2290         }
2291         return field;
2292     }
2293 
2294 
2295     /**
2296      * Returns a {@code Method} object that reflects the specified
2297      * declared method of the class or interface represented by this
2298      * {@code Class} object. The {@code name} parameter is a
2299      * {@code String} that specifies the simple name of the desired
2300      * method, and the {@code parameterTypes} parameter is an array of
2301      * {@code Class} objects that identify the method's formal parameter
2302      * types, in declared order.  If more than one method with the same
2303      * parameter types is declared in a class, and one of these methods has a
2304      * return type that is more specific than any of the others, that method is
2305      * returned; otherwise one of the methods is chosen arbitrarily.  If the
2306      * name is "&lt;init&gt;"or "&lt;clinit&gt;" a {@code NoSuchMethodException}
2307      * is raised.
2308      *
2309      * <p> If this {@code Class} object represents an array type, then this
2310      * method does not find the {@code clone()} method.
2311      *


2331      *          <li> the caller's class loader is not the same as or an
2332      *          ancestor of the class loader for the current class and
2333      *          invocation of {@link SecurityManager#checkPackageAccess
2334      *          s.checkPackageAccess()} denies access to the package
2335      *          of this class
2336      *
2337      *          </ul>
2338      *
2339      * @jls 8.2 Class Members
2340      * @jls 8.4 Method Declarations
2341      * @since 1.1
2342      */
2343     @CallerSensitive
2344     public Method getDeclaredMethod(String name, Class<?>... parameterTypes)
2345         throws NoSuchMethodException, SecurityException {
2346         checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
2347         Method method = searchMethods(privateGetDeclaredMethods(false), name, parameterTypes);
2348         if (method == null) {
2349             throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes));
2350         }
2351         return method;
2352     }
2353 
2354 
2355     /**
2356      * Returns a {@code Constructor} object that reflects the specified
2357      * constructor of the class or interface represented by this
2358      * {@code Class} object.  The {@code parameterTypes} parameter is
2359      * an array of {@code Class} objects that identify the constructor's
2360      * formal parameter types, in declared order.
2361      *
2362      * If this {@code Class} object represents an inner class
2363      * declared in a non-static context, the formal parameter types
2364      * include the explicit enclosing instance as the first parameter.
2365      *
2366      * @param parameterTypes the parameter array
2367      * @return  The {@code Constructor} object for the constructor with the
2368      *          specified parameter list
2369      * @throws  NoSuchMethodException if a matching method is not found.
2370      * @throws  SecurityException
2371      *          If a security manager, <i>s</i>, is present and any of the


2377      *          class loader of this class and invocation of
2378      *          {@link SecurityManager#checkPermission
2379      *          s.checkPermission} method with
2380      *          {@code RuntimePermission("accessDeclaredMembers")}
2381      *          denies access to the declared constructor
2382      *
2383      *          <li> the caller's class loader is not the same as or an
2384      *          ancestor of the class loader for the current class and
2385      *          invocation of {@link SecurityManager#checkPackageAccess
2386      *          s.checkPackageAccess()} denies access to the package
2387      *          of this class
2388      *
2389      *          </ul>
2390      *
2391      * @since 1.1
2392      */
2393     @CallerSensitive
2394     public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)
2395         throws NoSuchMethodException, SecurityException {
2396         checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
2397         return getConstructor0(parameterTypes, Member.DECLARED);

2398     }
2399 
2400     /**
2401      * Finds a resource with a given name.
2402      *
2403      * <p> If this class is in a named {@link Module Module} then this method
2404      * will attempt to find the resource in the module by means of the absolute
2405      * resource name, subject to the rules for encapsulation specified in the
2406      * {@code Module} {@link Module#getResourceAsStream getResourceAsStream}
2407      * method.
2408      *
2409      * <p> Otherwise, if this class is not in a named module then the rules for
2410      * searching resources associated with a given class are implemented by the
2411      * defining {@linkplain ClassLoader class loader} of the class.  This method
2412      * delegates to this object's class loader.  If this object was loaded by
2413      * the bootstrap class loader, the method delegates to {@link
2414      * ClassLoader#getSystemResourceAsStream}.
2415      *
2416      * <p> Before finding a resource in the caller's module or delegation to a
2417      * class loader, an absolute resource name is constructed from the given


2987     // via ReflectionFactory.copyMethod.
2988     private Method[] privateGetDeclaredMethods(boolean publicOnly) {
2989         Method[] res;
2990         ReflectionData<T> rd = reflectionData();
2991         if (rd != null) {
2992             res = publicOnly ? rd.declaredPublicMethods : rd.declaredMethods;
2993             if (res != null) return res;
2994         }
2995         // No cached value available; request value from VM
2996         res = Reflection.filterMethods(this, getDeclaredMethods0(publicOnly));
2997         if (rd != null) {
2998             if (publicOnly) {
2999                 rd.declaredPublicMethods = res;
3000             } else {
3001                 rd.declaredMethods = res;
3002             }
3003         }
3004         return res;
3005     }
3006 
3007     static class MethodArray {
3008         // Don't add or remove methods except by add() or remove() calls.
3009         private Method[] methods;
3010         private int length;
3011         private int defaults;
3012 
3013         MethodArray() {
3014             this(20);
3015         }
3016 
3017         MethodArray(int initialSize) {
3018             if (initialSize < 2)
3019                 throw new IllegalArgumentException("Size should be 2 or more");
3020 
3021             methods = new Method[initialSize];
3022             length = 0;
3023             defaults = 0;
3024         }
3025 
3026         boolean hasDefaults() {
3027             return defaults != 0;
3028         }
3029 
3030         void add(Method m) {
3031             if (length == methods.length) {
3032                 methods = Arrays.copyOf(methods, 2 * methods.length);
3033             }
3034             methods[length++] = m;
3035 
3036             if (m != null && m.isDefault())
3037                 defaults++;
3038         }
3039 
3040         void addAll(Method[] ma) {
3041             for (Method m : ma) {
3042                 add(m);
3043             }
3044         }
3045 
3046         void addAll(MethodArray ma) {
3047             for (int i = 0; i < ma.length(); i++) {
3048                 add(ma.get(i));
3049             }
3050         }
3051 
3052         void addIfNotPresent(Method newMethod) {
3053             for (int i = 0; i < length; i++) {
3054                 Method m = methods[i];
3055                 if (m == newMethod || (m != null && m.equals(newMethod))) {
3056                     return;
3057                 }
3058             }
3059             add(newMethod);
3060         }
3061 
3062         void addAllIfNotPresent(MethodArray newMethods) {
3063             for (int i = 0; i < newMethods.length(); i++) {
3064                 Method m = newMethods.get(i);
3065                 if (m != null) {
3066                     addIfNotPresent(m);
3067                 }
3068             }
3069         }
3070 
3071         /* Add Methods declared in an interface to this MethodArray.
3072          * Static methods declared in interfaces are not inherited.
3073          */
3074         void addInterfaceMethods(Method[] methods) {
3075             for (Method candidate : methods) {
3076                 if (!Modifier.isStatic(candidate.getModifiers())) {
3077                     add(candidate);
3078                 }
3079             }
3080         }
3081 
3082         int length() {
3083             return length;
3084         }
3085 
3086         Method get(int i) {
3087             return methods[i];
3088         }
3089 
3090         Method getFirst() {
3091             for (Method m : methods)
3092                 if (m != null)
3093                     return m;
3094             return null;
3095         }
3096 
3097         void removeByNameAndDescriptor(Method toRemove) {
3098             for (int i = 0; i < length; i++) {
3099                 Method m = methods[i];
3100                 if (m != null && matchesNameAndDescriptor(m, toRemove)) {
3101                     remove(i);
3102                 }
3103             }
3104         }
3105 
3106         private void remove(int i) {
3107             if (methods[i] != null && methods[i].isDefault())
3108                 defaults--;
3109                     methods[i] = null;
3110                 }
3111 
3112         private boolean matchesNameAndDescriptor(Method m1, Method m2) {
3113             return m1.getReturnType() == m2.getReturnType() &&
3114                    m1.getName() == m2.getName() && // name is guaranteed to be interned
3115                    arrayContentsEq(m1.getParameterTypes(),
3116                            m2.getParameterTypes());
3117             }
3118 
3119         void compactAndTrim() {
3120             int newPos = 0;
3121             // Get rid of null slots
3122             for (int pos = 0; pos < length; pos++) {
3123                 Method m = methods[pos];
3124                 if (m != null) {
3125                     if (pos != newPos) {
3126                         methods[newPos] = m;
3127                     }
3128                     newPos++;
3129                 }
3130             }
3131             if (newPos != methods.length) {
3132                 methods = Arrays.copyOf(methods, newPos);
3133             }
3134         }
3135 
3136         /* Removes all Methods from this MethodArray that have a more specific
3137          * default Method in this MethodArray.
3138          *
3139          * Users of MethodArray are responsible for pruning Methods that have
3140          * a more specific <em>concrete</em> Method.
3141          */
3142         void removeLessSpecifics() {
3143             if (!hasDefaults())
3144                 return;
3145 
3146             for (int i = 0; i < length; i++) {
3147                 Method m = get(i);
3148                 if  (m == null || !m.isDefault())
3149                     continue;
3150 
3151                 for (int j  = 0; j < length; j++) {
3152                     if (i == j)
3153                         continue;
3154 
3155                     Method candidate = get(j);
3156                     if (candidate == null)
3157                         continue;
3158 
3159                     if (!matchesNameAndDescriptor(m, candidate))
3160                         continue;
3161 
3162                     if (hasMoreSpecificClass(m, candidate))
3163                         remove(j);
3164                 }
3165             }
3166         }
3167 
3168         Method[] getArray() {
3169             return methods;
3170         }
3171 
3172         // Returns true if m1 is more specific than m2
3173         static boolean hasMoreSpecificClass(Method m1, Method m2) {
3174             Class<?> m1Class = m1.getDeclaringClass();
3175             Class<?> m2Class = m2.getDeclaringClass();
3176             return m1Class != m2Class && m2Class.isAssignableFrom(m1Class);
3177         }
3178     }
3179 
3180 
3181     // Returns an array of "root" methods. These Method objects must NOT
3182     // be propagated to the outside world, but must instead be copied
3183     // via ReflectionFactory.copyMethod.
3184     private Method[] privateGetPublicMethods() {
3185         Method[] res;
3186         ReflectionData<T> rd = reflectionData();
3187         if (rd != null) {
3188             res = rd.publicMethods;
3189             if (res != null) return res;
3190         }
3191 
3192         // No cached value available; compute value recursively.
3193         // Start by fetching public declared methods
3194         MethodArray methods = new MethodArray();
3195         {
3196             Method[] tmp = privateGetDeclaredMethods(true);
3197             methods.addAll(tmp);














3198         }
3199         // Now recur over superclass and direct superinterfaces.
3200         // Go over superinterfaces first so we can more easily filter
3201         // out concrete implementations inherited from superclasses at
3202         // the end.
3203         MethodArray inheritedMethods = new MethodArray();
3204         for (Class<?> i : getInterfaces()) {
3205             inheritedMethods.addInterfaceMethods(i.privateGetPublicMethods());
3206         }
3207         if (!isInterface()) {
3208             Class<?> c = getSuperclass();
3209             if (c != null) {
3210                 MethodArray supers = new MethodArray();
3211                 supers.addAll(c.privateGetPublicMethods());
3212                 // Filter out concrete implementations of any
3213                 // interface methods
3214                 for (int i = 0; i < supers.length(); i++) {
3215                     Method m = supers.get(i);
3216                     if (m != null &&
3217                             !Modifier.isAbstract(m.getModifiers()) &&
3218                             !m.isDefault()) {
3219                         inheritedMethods.removeByNameAndDescriptor(m);
3220                     }
3221                 }
3222                 // Insert superclass's inherited methods before
3223                 // superinterfaces' to satisfy getMethod's search
3224                 // order
3225                 supers.addAll(inheritedMethods);
3226                 inheritedMethods = supers;
3227             }
3228         }
3229         // Filter out all local methods from inherited ones
3230         for (int i = 0; i < methods.length(); i++) {
3231             Method m = methods.get(i);
3232             inheritedMethods.removeByNameAndDescriptor(m);
3233         }
3234         methods.addAllIfNotPresent(inheritedMethods);
3235         methods.removeLessSpecifics();
3236         methods.compactAndTrim();
3237         res = methods.getArray();
3238         if (rd != null) {
3239             rd.publicMethods = res;
3240         }
3241         return res;
3242     }
3243 
3244 
3245     //
3246     // Helpers for fetchers of one field, method, or constructor
3247     //
3248 

3249     private static Field searchFields(Field[] fields, String name) {
3250         String internedName = name.intern();
3251         for (Field field : fields) {
3252             if (field.getName() == internedName) {
3253                 return getReflectionFactory().copyField(field);
3254             }
3255         }
3256         return null;
3257     }
3258 
3259     private Field getField0(String name) throws NoSuchFieldException {



3260         // Note: the intent is that the search algorithm this routine
3261         // uses be equivalent to the ordering imposed by
3262         // privateGetPublicFields(). It fetches only the declared
3263         // public fields for each class, however, to reduce the number
3264         // of Field objects which have to be created for the common
3265         // case where the field being requested is declared in the
3266         // class which is being queried.
3267         Field res;
3268         // Search declared public fields
3269         if ((res = searchFields(privateGetDeclaredFields(true), name)) != null) {
3270             return res;
3271         }
3272         // Direct superinterfaces, recursively
3273         Class<?>[] interfaces = getInterfaces();
3274         for (Class<?> c : interfaces) {
3275             if ((res = c.getField0(name)) != null) {
3276                 return res;
3277             }
3278         }
3279         // Direct superclass, recursively
3280         if (!isInterface()) {
3281             Class<?> c = getSuperclass();
3282             if (c != null) {
3283                 if ((res = c.getField0(name)) != null) {
3284                     return res;
3285                 }
3286             }
3287         }
3288         return null;
3289     }
3290 

3291     private static Method searchMethods(Method[] methods,
3292                                         String name,
3293                                         Class<?>[] parameterTypes)
3294     {

3295         Method res = null;
3296         String internedName = name.intern();
3297         for (Method m : methods) {
3298             if (m.getName() == internedName
3299                 && arrayContentsEq(parameterTypes, m.getParameterTypes())

3300                 && (res == null
3301                     || res.getReturnType().isAssignableFrom(m.getReturnType())))

3302                 res = m;
3303         }
3304 
3305         return (res == null ? res : getReflectionFactory().copyMethod(res));
3306     }
3307 
3308     private Method getMethod0(String name, Class<?>[] parameterTypes, boolean includeStaticMethods) {
3309         MethodArray interfaceCandidates = new MethodArray(2);
3310         Method res =  privateGetMethodRecursive(name, parameterTypes, includeStaticMethods, interfaceCandidates);
3311         if (res != null)
3312             return res;
3313 
3314         // Not found on class or superclass directly
3315         interfaceCandidates.removeLessSpecifics();
3316         return interfaceCandidates.getFirst(); // may be null






3317     }
3318 
3319     private Method privateGetMethodRecursive(String name,



3320             Class<?>[] parameterTypes,
3321             boolean includeStaticMethods,
3322             MethodArray allInterfaceCandidates) {
3323         // Note: the intent is that the search algorithm this routine
3324         // uses be equivalent to the ordering imposed by
3325         // privateGetPublicMethods(). It fetches only the declared
3326         // public methods for each class, however, to reduce the
3327         // number of Method objects which have to be created for the
3328         // common case where the method being requested is declared in
3329         // the class which is being queried.
3330         //
3331         // Due to default methods, unless a method is found on a superclass,
3332         // methods declared in any superinterface needs to be considered.
3333         // Collect all candidates declared in superinterfaces in {@code
3334         // allInterfaceCandidates} and select the most specific if no match on
3335         // a superclass is found.
3336 
3337         // Must _not_ return root methods
3338         Method res;
3339         // Search declared public methods
3340         if ((res = searchMethods(privateGetDeclaredMethods(true),
3341                                  name,
3342                                  parameterTypes)) != null) {
3343             if (includeStaticMethods || !Modifier.isStatic(res.getModifiers()))
3344                 return res;
3345         }
3346         // Search superclass's methods
3347         if (!isInterface()) {
3348             Class<? super T> c = getSuperclass();
3349             if (c != null) {
3350                 if ((res = c.getMethod0(name, parameterTypes, true)) != null) {
3351                     return res;
3352                 }







3353             }
3354         }
3355         // Search superinterfaces' methods
3356         Class<?>[] interfaces = getInterfaces();
3357         for (Class<?> c : interfaces)
3358             if ((res = c.getMethod0(name, parameterTypes, false)) != null)
3359                 allInterfaceCandidates.add(res);
3360         // Not found
3361         return null;
3362     }
3363 



3364     private Constructor<T> getConstructor0(Class<?>[] parameterTypes,
3365                                         int which) throws NoSuchMethodException
3366     {

3367         Constructor<T>[] constructors = privateGetDeclaredConstructors((which == Member.PUBLIC));
3368         for (Constructor<T> constructor : constructors) {
3369             if (arrayContentsEq(parameterTypes,
3370                                 constructor.getParameterTypes())) {
3371                 return getReflectionFactory().copyConstructor(constructor);
3372             }
3373         }
3374         throw new NoSuchMethodException(getName() + ".<init>" + argumentTypesToString(parameterTypes));
3375     }
3376 
3377     //
3378     // Other helpers and base implementation
3379     //
3380 
3381     private static boolean arrayContentsEq(Object[] a1, Object[] a2) {
3382         if (a1 == null) {
3383             return a2 == null || a2.length == 0;
3384         }
3385 
3386         if (a2 == null) {
3387             return a1.length == 0;
3388         }
3389 
3390         if (a1.length != a2.length) {
3391             return false;


< prev index next >