1 /*
  2  * Copyright (c) 1996, 2024, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.  Oracle designates this
  8  * particular file as subject to the "Classpath" exception as provided
  9  * by Oracle in the LICENSE file that accompanied this code.
 10  *
 11  * This code is distributed in the hope that it will be useful, but WITHOUT
 12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 14  * version 2 for more details (a copy is included in the LICENSE file that
 15  * accompanied this code).
 16  *
 17  * You should have received a copy of the GNU General Public License version
 18  * 2 along with this work; if not, write to the Free Software Foundation,
 19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 20  *
 21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 22  * or visit www.oracle.com if you need additional information or have any
 23  * questions.
 24  */
 25 
 26 package java.lang.reflect;
 27 
 28 import jdk.internal.access.SharedSecrets;
 29 import jdk.internal.misc.VM;
 30 import jdk.internal.reflect.CallerSensitive;
 31 import jdk.internal.reflect.CallerSensitiveAdapter;
 32 import jdk.internal.reflect.MethodAccessor;
 33 import jdk.internal.reflect.Reflection;
 34 import jdk.internal.vm.annotation.ForceInline;
 35 import jdk.internal.vm.annotation.IntrinsicCandidate;
 36 import jdk.internal.vm.annotation.Stable;
 37 import sun.reflect.annotation.ExceptionProxy;
 38 import sun.reflect.annotation.TypeNotPresentExceptionProxy;
 39 import sun.reflect.generics.repository.GenericDeclRepository;
 40 import sun.reflect.generics.repository.MethodRepository;
 41 import sun.reflect.generics.factory.CoreReflectionFactory;
 42 import sun.reflect.generics.factory.GenericsFactory;
 43 import sun.reflect.generics.scope.MethodScope;
 44 import sun.reflect.annotation.AnnotationType;
 45 import sun.reflect.annotation.AnnotationParser;
 46 import java.lang.annotation.Annotation;
 47 import java.lang.annotation.AnnotationFormatError;
 48 import java.lang.reflect.code.op.ExtendedOp;
 49 import java.lang.reflect.code.Op;
 50 import java.lang.reflect.code.parser.OpParser;
 51 import java.nio.ByteBuffer;
 52 import java.util.List;
 53 import java.util.Optional;
 54 import java.util.StringJoiner;
 55 
 56 import static java.lang.reflect.code.op.CoreOp.*;
 57 
 58 /**
 59  * A {@code Method} provides information about, and access to, a single method
 60  * on a class or interface.  The reflected method may be a class method
 61  * or an instance method (including an abstract method).
 62  *
 63  * <p>A {@code Method} permits widening conversions to occur when matching the
 64  * actual parameters to invoke with the underlying method's formal
 65  * parameters, but it throws an {@code IllegalArgumentException} if a
 66  * narrowing conversion would occur.
 67  *
 68  * @see Member
 69  * @see java.lang.Class
 70  * @see java.lang.Class#getMethods()
 71  * @see java.lang.Class#getMethod(String, Class[])
 72  * @see java.lang.Class#getDeclaredMethods()
 73  * @see java.lang.Class#getDeclaredMethod(String, Class[])
 74  *
 75  * @author Kenneth Russell
 76  * @author Nakul Saraiya
 77  * @since 1.1
 78  */
 79 public final class Method extends Executable {
 80     private final Class<?>            clazz;
 81     private final int                 slot;
 82     // This is guaranteed to be interned by the VM in the 1.4
 83     // reflection implementation
 84     private final String              name;
 85     private final Class<?>            returnType;
 86     private final Class<?>[]          parameterTypes;
 87     private final Class<?>[]          exceptionTypes;
 88     private final int                 modifiers;
 89     // Generics and annotations support
 90     private final transient String    signature;
 91     // generic info repository; lazily initialized
 92     private transient volatile MethodRepository genericInfo;
 93     private final byte[]              annotations;
 94     private final byte[]              parameterAnnotations;
 95     private final byte[]              annotationDefault;
 96     @Stable
 97     private MethodAccessor      methodAccessor;
 98     // For sharing of MethodAccessors. This branching structure is
 99     // currently only two levels deep (i.e., one root Method and
100     // potentially many Method objects pointing to it.)
101     //
102     // If this branching structure would ever contain cycles, deadlocks can
103     // occur in annotation code.
104     private Method              root;
105     private volatile Optional<FuncOp>     codeModel;
106 
107     // Generics infrastructure
108     private String getGenericSignature() {return signature;}
109 
110     // Accessor for factory
111     private GenericsFactory getFactory() {
112         // create scope and factory
113         return CoreReflectionFactory.make(this, MethodScope.make(this));
114     }
115 
116     // Accessor for generic info repository
117     @Override
118     MethodRepository getGenericInfo() {
119         var genericInfo = this.genericInfo;
120         // lazily initialize repository if necessary
121         if (genericInfo == null) {
122             // create and cache generic info repository
123             genericInfo = MethodRepository.make(getGenericSignature(),
124                                                 getFactory());
125             this.genericInfo = genericInfo;
126         }
127         return genericInfo; //return cached repository
128     }
129 
130     /**
131      * Package-private constructor
132      */
133     Method(Class<?> declaringClass,
134            String name,
135            Class<?>[] parameterTypes,
136            Class<?> returnType,
137            Class<?>[] checkedExceptions,
138            int modifiers,
139            int slot,
140            String signature,
141            byte[] annotations,
142            byte[] parameterAnnotations,
143            byte[] annotationDefault) {
144         this.clazz = declaringClass;
145         this.name = name;
146         this.parameterTypes = parameterTypes;
147         this.returnType = returnType;
148         this.exceptionTypes = checkedExceptions;
149         this.modifiers = modifiers;
150         this.slot = slot;
151         this.signature = signature;
152         this.annotations = annotations;
153         this.parameterAnnotations = parameterAnnotations;
154         this.annotationDefault = annotationDefault;
155     }
156 
157     /**
158      * Package-private routine (exposed to java.lang.Class via
159      * ReflectAccess) which returns a copy of this Method. The copy's
160      * "root" field points to this Method.
161      */
162     Method copy() {
163         // This routine enables sharing of MethodAccessor objects
164         // among Method objects which refer to the same underlying
165         // method in the VM. (All of this contortion is only necessary
166         // because of the "accessibility" bit in AccessibleObject,
167         // which implicitly requires that new java.lang.reflect
168         // objects be fabricated for each reflective call on Class
169         // objects.)
170         if (this.root != null)
171             throw new IllegalArgumentException("Can not copy a non-root Method");
172 
173         Method res = new Method(clazz, name, parameterTypes, returnType,
174                                 exceptionTypes, modifiers, slot, signature,
175                                 annotations, parameterAnnotations, annotationDefault);
176         res.root = this;
177         // Might as well eagerly propagate this if already present
178         res.methodAccessor = methodAccessor;
179         return res;
180     }
181 
182     /**
183      * Make a copy of a leaf method.
184      */
185     Method leafCopy() {
186         if (this.root == null)
187             throw new IllegalArgumentException("Can only leafCopy a non-root Method");
188 
189         Method res = new Method(clazz, name, parameterTypes, returnType,
190                 exceptionTypes, modifiers, slot, signature,
191                 annotations, parameterAnnotations, annotationDefault);
192         res.root = root;
193         res.methodAccessor = methodAccessor;
194         return res;
195     }
196 
197     /**
198      * @throws InaccessibleObjectException {@inheritDoc}
199      * @throws SecurityException {@inheritDoc}
200      */
201     @Override
202     @CallerSensitive
203     public void setAccessible(boolean flag) {
204         AccessibleObject.checkPermission();
205         if (flag) checkCanSetAccessible(Reflection.getCallerClass());
206         setAccessible0(flag);
207     }
208 
209     @Override
210     void checkCanSetAccessible(Class<?> caller) {
211         checkCanSetAccessible(caller, clazz);
212     }
213 
214     @Override
215     Method getRoot() {
216         return root;
217     }
218 
219     @Override
220     boolean hasGenericInformation() {
221         return (getGenericSignature() != null);
222     }
223 
224     @Override
225     byte[] getAnnotationBytes() {
226         return annotations;
227     }
228 
229     /**
230      * Returns the {@code Class} object representing the class or interface
231      * that declares the method represented by this object.
232      */
233     @Override
234     public Class<?> getDeclaringClass() {
235         return clazz;
236     }
237 
238     /**
239      * Returns the name of the method represented by this {@code Method}
240      * object, as a {@code String}.
241      */
242     @Override
243     public String getName() {
244         return name;
245     }
246 
247     /**
248      * {@inheritDoc}
249      * @jls 8.4.3 Method Modifiers
250      */
251     @Override
252     public int getModifiers() {
253         return modifiers;
254     }
255 
256     /**
257      * Returns the code model of the method body, if present.
258      * @return the code model of the method body.
259      * @since 99
260      */
261     // @@@ Make caller sensitive with the same access control as invoke
262     // and throwing IllegalAccessException
263 //    @CallerSensitive
264     public Optional<FuncOp> getCodeModel() {
265         Optional<FuncOp> localRef = codeModel;
266         if (localRef == null) {
267             synchronized (this) {
268                 localRef = codeModel;
269                 if (localRef == null) {
270                     Optional<FuncOp> op = createCodeModel();
271                     codeModel = localRef = op;
272                 }
273             }
274         }
275         return localRef;
276     }
277 
278     private Optional<FuncOp> createCodeModel() {
279         Class<?> dc = getDeclaringClass();
280         String fieldName = getName() + "$" + "op";
281         Field f;
282         try {
283             f = dc.getDeclaredField(fieldName);
284         } catch (NoSuchFieldException e) {
285             return Optional.empty();
286         }
287 
288         String modelText;
289         try {
290             // @@@ Use method handle with full power mode
291             f.setAccessible(true);
292             modelText = (String) f.get(null);
293         } catch (IllegalAccessException e) {
294             throw new RuntimeException(e);
295         }
296 
297         FuncOp op;
298         try {
299             List<Op> ops = OpParser.fromString(ExtendedOp.FACTORY, modelText);
300             op = (FuncOp) ops.get(0);
301         } catch (RuntimeException e) {
302             // @@@ Error or Exception?
303             throw e;
304         }
305         return Optional.of(op);
306     }
307 
308     /**
309      * {@inheritDoc}
310      * @throws GenericSignatureFormatError {@inheritDoc}
311      * @since 1.5
312      * @jls 8.4.4 Generic Methods
313      */
314     @Override
315     @SuppressWarnings({"rawtypes", "unchecked"})
316     public TypeVariable<Method>[] getTypeParameters() {
317         if (getGenericSignature() != null)
318             return (TypeVariable<Method>[])getGenericInfo().getTypeParameters();
319         else
320             return (TypeVariable<Method>[])GenericDeclRepository.EMPTY_TYPE_VARS;
321     }
322 
323     /**
324      * Returns a {@code Class} object that represents the formal return type
325      * of the method represented by this {@code Method} object.
326      *
327      * @return the return type for the method this object represents
328      */
329     public Class<?> getReturnType() {
330         return returnType;
331     }
332 
333     /**
334      * Returns a {@code Type} object that represents the formal return
335      * type of the method represented by this {@code Method} object.
336      *
337      * <p>If the return type is a parameterized type,
338      * the {@code Type} object returned must accurately reflect
339      * the actual type arguments used in the source code.
340      *
341      * <p>If the return type is a type variable or a parameterized type, it
342      * is created. Otherwise, it is resolved.
343      *
344      * @return  a {@code Type} object that represents the formal return
345      *     type of the underlying  method
346      * @throws GenericSignatureFormatError
347      *     if the generic method signature does not conform to the format
348      *     specified in
349      *     <cite>The Java Virtual Machine Specification</cite>
350      * @throws TypeNotPresentException if the underlying method's
351      *     return type refers to a non-existent class or interface declaration
352      * @throws MalformedParameterizedTypeException if the
353      *     underlying method's return type refers to a parameterized
354      *     type that cannot be instantiated for any reason
355      * @since 1.5
356      */
357     public Type getGenericReturnType() {
358       if (getGenericSignature() != null) {
359         return getGenericInfo().getReturnType();
360       } else { return getReturnType();}
361     }
362 
363     @Override
364     Class<?>[] getSharedParameterTypes() {
365         return parameterTypes;
366     }
367 
368     @Override
369     Class<?>[] getSharedExceptionTypes() {
370         return exceptionTypes;
371     }
372 
373     /**
374      * {@inheritDoc}
375      */
376     @Override
377     public Class<?>[] getParameterTypes() {
378         return parameterTypes.clone();
379     }
380 
381     /**
382      * {@inheritDoc}
383      * @since 1.8
384      */
385     public int getParameterCount() { return parameterTypes.length; }
386 
387 
388     /**
389      * {@inheritDoc}
390      * @throws GenericSignatureFormatError {@inheritDoc}
391      * @throws TypeNotPresentException {@inheritDoc}
392      * @throws MalformedParameterizedTypeException {@inheritDoc}
393      * @since 1.5
394      */
395     @Override
396     public Type[] getGenericParameterTypes() {
397         return super.getGenericParameterTypes();
398     }
399 
400     /**
401      * {@inheritDoc}
402      */
403     @Override
404     public Class<?>[] getExceptionTypes() {
405         return exceptionTypes.clone();
406     }
407 
408     /**
409      * {@inheritDoc}
410      * @throws GenericSignatureFormatError {@inheritDoc}
411      * @throws TypeNotPresentException {@inheritDoc}
412      * @throws MalformedParameterizedTypeException {@inheritDoc}
413      * @since 1.5
414      */
415     @Override
416     public Type[] getGenericExceptionTypes() {
417         return super.getGenericExceptionTypes();
418     }
419 
420     /**
421      * Compares this {@code Method} against the specified object.  Returns
422      * true if the objects are the same.  Two {@code Methods} are the same if
423      * they were declared by the same class and have the same name
424      * and formal parameter types and return type.
425      */
426     public boolean equals(Object obj) {
427         if (obj instanceof Method other) {
428             if ((getDeclaringClass() == other.getDeclaringClass())
429                 && (getName() == other.getName())) {
430                 if (!returnType.equals(other.getReturnType()))
431                     return false;
432                 return equalParamTypes(parameterTypes, other.parameterTypes);
433             }
434         }
435         return false;
436     }
437 
438     /**
439      * Returns a hashcode for this {@code Method}.  The hashcode is computed
440      * as the exclusive-or of the hashcodes for the underlying
441      * method's declaring class name and the method's name.
442      */
443     public int hashCode() {
444         return getDeclaringClass().getName().hashCode() ^ getName().hashCode();
445     }
446 
447     /**
448      * Returns a string describing this {@code Method}.  The string is
449      * formatted as the method access modifiers, if any, followed by
450      * the method return type, followed by a space, followed by the
451      * class declaring the method, followed by a period, followed by
452      * the method name, followed by a parenthesized, comma-separated
453      * list of the method's formal parameter types. If the method
454      * throws checked exceptions, the parameter list is followed by a
455      * space, followed by the word "{@code throws}" followed by a
456      * comma-separated list of the thrown exception types.
457      * For example:
458      * <pre>
459      *    public boolean java.lang.Object.equals(java.lang.Object)
460      * </pre>
461      *
462      * <p>The access modifiers are placed in canonical order as
463      * specified by "The Java Language Specification".  This is
464      * {@code public}, {@code protected} or {@code private} first,
465      * and then other modifiers in the following order:
466      * {@code abstract}, {@code default}, {@code static}, {@code final},
467      * {@code synchronized}, {@code native}, {@code strictfp}.
468      *
469      * @return a string describing this {@code Method}
470      *
471      * @jls 8.4.3 Method Modifiers
472      * @jls 9.4 Method Declarations
473      * @jls 9.6.1 Annotation Interface Elements
474      */
475     public String toString() {
476         return sharedToString(Modifier.methodModifiers(),
477                               isDefault(),
478                               parameterTypes,
479                               exceptionTypes);
480     }
481 
482     @Override
483     void specificToStringHeader(StringBuilder sb) {
484         sb.append(getReturnType().getTypeName()).append(' ');
485         sb.append(getDeclaringClass().getTypeName()).append('.');
486         sb.append(getName());
487     }
488 
489     @Override
490     String toShortString() {
491         return "method " + getDeclaringClass().getTypeName() +
492                 '.' + toShortSignature();
493     }
494 
495     String toShortSignature() {
496         StringJoiner sj = new StringJoiner(",", getName() + "(", ")");
497         for (Class<?> parameterType : getSharedParameterTypes()) {
498             sj.add(parameterType.getTypeName());
499         }
500         return sj.toString();
501     }
502 
503     /**
504      * Returns a string describing this {@code Method}, including type
505      * parameters.  The string is formatted as the method access
506      * modifiers, if any, followed by an angle-bracketed
507      * comma-separated list of the method's type parameters, if any,
508      * including informative bounds of the type parameters, if any,
509      * followed by the method's generic return type, followed by a
510      * space, followed by the class declaring the method, followed by
511      * a period, followed by the method name, followed by a
512      * parenthesized, comma-separated list of the method's generic
513      * formal parameter types.
514      *
515      * If this method was declared to take a variable number of
516      * arguments, instead of denoting the last parameter as
517      * "<code><i>Type</i>[]</code>", it is denoted as
518      * "<code><i>Type</i>...</code>".
519      *
520      * A space is used to separate access modifiers from one another
521      * and from the type parameters or return type.  If there are no
522      * type parameters, the type parameter list is elided; if the type
523      * parameter list is present, a space separates the list from the
524      * class name.  If the method is declared to throw exceptions, the
525      * parameter list is followed by a space, followed by the word
526      * "{@code throws}" followed by a comma-separated list of the generic
527      * thrown exception types.
528      *
529      * <p>The access modifiers are placed in canonical order as
530      * specified by "The Java Language Specification".  This is
531      * {@code public}, {@code protected} or {@code private} first,
532      * and then other modifiers in the following order:
533      * {@code abstract}, {@code default}, {@code static}, {@code final},
534      * {@code synchronized}, {@code native}, {@code strictfp}.
535      *
536      * @return a string describing this {@code Method},
537      * include type parameters
538      *
539      * @since 1.5
540      *
541      * @jls 8.4.3 Method Modifiers
542      * @jls 9.4 Method Declarations
543      * @jls 9.6.1 Annotation Interface Elements
544      */
545     @Override
546     public String toGenericString() {
547         return sharedToGenericString(Modifier.methodModifiers(), isDefault());
548     }
549 
550     @Override
551     void specificToGenericStringHeader(StringBuilder sb) {
552         Type genRetType = getGenericReturnType();
553         sb.append(genRetType.getTypeName()).append(' ');
554         sb.append(getDeclaringClass().getTypeName()).append('.');
555         sb.append(getName());
556     }
557 
558     /**
559      * Invokes the underlying method represented by this {@code Method}
560      * object, on the specified object with the specified parameters.
561      * Individual parameters are automatically unwrapped to match
562      * primitive formal parameters, and both primitive and reference
563      * parameters are subject to method invocation conversions as
564      * necessary.
565      *
566      * <p>If the underlying method is static, then the specified {@code obj}
567      * argument is ignored. It may be null.
568      *
569      * <p>If the number of formal parameters required by the underlying method is
570      * 0, the supplied {@code args} array may be of length 0 or null.
571      *
572      * <p>If the underlying method is an instance method, it is invoked
573      * using dynamic method lookup as documented in The Java Language
574      * Specification, section {@jls 15.12.4.4}; in particular,
575      * overriding based on the runtime type of the target object may occur.
576      *
577      * <p>If the underlying method is static, the class that declared
578      * the method is initialized if it has not already been initialized.
579      *
580      * <p>If the method completes normally, the value it returns is
581      * returned to the caller of invoke; if the value has a primitive
582      * type, it is first appropriately wrapped in an object. However,
583      * if the value has the type of an array of a primitive type, the
584      * elements of the array are <i>not</i> wrapped in objects; in
585      * other words, an array of primitive type is returned.  If the
586      * underlying method return type is void, the invocation returns
587      * null.
588      *
589      * @param obj  the object the underlying method is invoked from
590      * @param args the arguments used for the method call
591      * @return the result of dispatching the method represented by
592      * this object on {@code obj} with parameters
593      * {@code args}
594      *
595      * @throws    IllegalAccessException    if this {@code Method} object
596      *              is enforcing Java language access control and the underlying
597      *              method is inaccessible.
598      * @throws    IllegalArgumentException  if the method is an
599      *              instance method and the specified object argument
600      *              is not an instance of the class or interface
601      *              declaring the underlying method (or of a subclass
602      *              or implementor thereof); if the number of actual
603      *              and formal parameters differ; if an unwrapping
604      *              conversion for primitive arguments fails; or if,
605      *              after possible unwrapping, a parameter value
606      *              cannot be converted to the corresponding formal
607      *              parameter type by a method invocation conversion.
608      * @throws    InvocationTargetException if the underlying method
609      *              throws an exception.
610      * @throws    NullPointerException      if the specified object is null
611      *              and the method is an instance method.
612      * @throws    ExceptionInInitializerError if the initialization
613      * provoked by this method fails.
614      */
615     @CallerSensitive
616     @ForceInline // to ensure Reflection.getCallerClass optimization
617     @IntrinsicCandidate
618     public Object invoke(Object obj, Object... args)
619         throws IllegalAccessException, InvocationTargetException
620     {
621         boolean callerSensitive = isCallerSensitive();
622         Class<?> caller = null;
623         if (!override || callerSensitive) {
624             caller = Reflection.getCallerClass();
625         }
626 
627         // Reflection::getCallerClass filters all subclasses of
628         // jdk.internal.reflect.MethodAccessorImpl and Method::invoke(Object, Object[])
629         // Should not call Method::invoke(Object, Object[], Class) here
630         if (!override) {
631             checkAccess(caller, clazz,
632                     Modifier.isStatic(modifiers) ? null : obj.getClass(),
633                     modifiers);
634         }
635         MethodAccessor ma = methodAccessor;             // read @Stable
636         if (ma == null) {
637             ma = acquireMethodAccessor();
638         }
639 
640         return callerSensitive ? ma.invoke(obj, args, caller) : ma.invoke(obj, args);
641     }
642 
643     /**
644      * This is to support MethodHandle calling caller-sensitive Method::invoke
645      * that may invoke a caller-sensitive method in order to get the original caller
646      * class (not the injected invoker).
647      *
648      * If this adapter is not presented, MethodHandle invoking Method::invoke
649      * will get an invoker class, a hidden nestmate of the original caller class,
650      * that becomes the caller class invoking Method::invoke.
651      */
652     @CallerSensitiveAdapter
653     private Object invoke(Object obj, Object[] args, Class<?> caller)
654             throws IllegalAccessException, InvocationTargetException
655     {
656         boolean callerSensitive = isCallerSensitive();
657         if (!override) {
658             checkAccess(caller, clazz,
659                         Modifier.isStatic(modifiers) ? null : obj.getClass(),
660                         modifiers);
661         }
662         MethodAccessor ma = methodAccessor;             // read @Stable
663         if (ma == null) {
664             ma = acquireMethodAccessor();
665         }
666 
667         return callerSensitive ? ma.invoke(obj, args, caller) : ma.invoke(obj, args);
668     }
669 
670     //  0 = not initialized (@Stable contract)
671     //  1 = initialized, CS
672     // -1 = initialized, not CS
673     @Stable private byte callerSensitive;
674 
675     private boolean isCallerSensitive() {
676         byte cs = callerSensitive;
677         if (cs == 0) {
678             callerSensitive = cs = (byte)(Reflection.isCallerSensitive(this) ? 1 : -1);
679         }
680         return (cs > 0);
681     }
682 
683     /**
684      * {@return {@code true} if this method is a bridge
685      * method; returns {@code false} otherwise}
686      *
687      * @apiNote
688      * A bridge method is a {@linkplain isSynthetic synthetic} method
689      * created by a Java compiler alongside a method originating from
690      * the source code. Bridge methods are used by Java compilers in
691      * various circumstances to span differences in Java programming
692      * language semantics and JVM semantics.
693      *
694      * <p>One example use of bridge methods is as a technique for a
695      * Java compiler to support <i>covariant overrides</i>, where a
696      * subclass overrides a method and gives the new method a more
697      * specific return type than the method in the superclass.  While
698      * the Java language specification forbids a class declaring two
699      * methods with the same parameter types but a different return
700      * type, the virtual machine does not. A common case where
701      * covariant overrides are used is for a {@link
702      * java.lang.Cloneable Cloneable} class where the {@link
703      * Object#clone() clone} method inherited from {@code
704      * java.lang.Object} is overridden and declared to return the type
705      * of the class. For example, {@code Object} declares
706      * <pre>{@code protected Object clone() throws CloneNotSupportedException {...}}</pre>
707      * and {@code EnumSet<E>} declares its language-level {@linkplain
708      * java.util.EnumSet#clone() covariant override}
709      * <pre>{@code public EnumSet<E> clone() {...}}</pre>
710      * If this technique was being used, the resulting class file for
711      * {@code EnumSet} would have two {@code clone} methods, one
712      * returning {@code EnumSet<E>} and the second a bridge method
713      * returning {@code Object}. The bridge method is a JVM-level
714      * override of {@code Object.clone()}.  The body of the {@code
715      * clone} bridge method calls its non-bridge counterpart and
716      * returns its result.
717      * @since 1.5
718      *
719      * @jls 8.4.8.3 Requirements in Overriding and Hiding
720      * @jls 15.12.4.5 Create Frame, Synchronize, Transfer Control
721      * @jvms 4.6 Methods
722      * @see <a
723      * href="{@docRoot}/java.base/java/lang/reflect/package-summary.html#LanguageJvmModel">Java
724      * programming language and JVM modeling in core reflection</a>
725      */
726     public boolean isBridge() {
727         return (getModifiers() & Modifier.BRIDGE) != 0;
728     }
729 
730     /**
731      * {@inheritDoc}
732      * @since 1.5
733      * @jls 8.4.1 Formal Parameters
734      */
735     @Override
736     public boolean isVarArgs() {
737         return super.isVarArgs();
738     }
739 
740     /**
741      * {@inheritDoc}
742      * @jls 13.1 The Form of a Binary
743      * @jvms 4.6 Methods
744      * @see <a
745      * href="{@docRoot}/java.base/java/lang/reflect/package-summary.html#LanguageJvmModel">Java
746      * programming language and JVM modeling in core reflection</a>
747      * @since 1.5
748      */
749     @Override
750     public boolean isSynthetic() {
751         return super.isSynthetic();
752     }
753 
754     /**
755      * Returns {@code true} if this method is a default
756      * method; returns {@code false} otherwise.
757      *
758      * A default method is a public non-abstract instance method, that
759      * is, a non-static method with a body, declared in an interface.
760      *
761      * @return true if and only if this method is a default
762      * method as defined by the Java Language Specification.
763      * @since 1.8
764      * @jls 9.4 Method Declarations
765      */
766     public boolean isDefault() {
767         // Default methods are public non-abstract instance methods
768         // declared in an interface.
769         return ((getModifiers() & (Modifier.ABSTRACT | Modifier.PUBLIC | Modifier.STATIC)) ==
770                 Modifier.PUBLIC) && getDeclaringClass().isInterface();
771     }
772 
773     // NOTE that there is no synchronization used here. It is correct
774     // (though not efficient) to generate more than one MethodAccessor
775     // for a given Method. However, avoiding synchronization will
776     // probably make the implementation more scalable.
777     private MethodAccessor acquireMethodAccessor() {
778         // First check to see if one has been created yet, and take it
779         // if so
780         Method root = this.root;
781         MethodAccessor tmp = root == null ? null : root.getMethodAccessor();
782         if (tmp != null) {
783             methodAccessor = tmp;
784         } else {
785             // Otherwise fabricate one and propagate it up to the root
786             tmp = reflectionFactory.newMethodAccessor(this, isCallerSensitive());
787             // set the method accessor only if it's not using native implementation
788             if (VM.isJavaLangInvokeInited())
789                 setMethodAccessor(tmp);
790         }
791 
792         return tmp;
793     }
794 
795     // Returns MethodAccessor for this Method object, not looking up
796     // the chain to the root
797     MethodAccessor getMethodAccessor() {
798         return methodAccessor;
799     }
800 
801     // Sets the MethodAccessor for this Method object and
802     // (recursively) its root
803     void setMethodAccessor(MethodAccessor accessor) {
804         methodAccessor = accessor;
805         // Propagate up
806         Method root = this.root;
807         if (root != null) {
808             root.setMethodAccessor(accessor);
809         }
810     }
811 
812     /**
813      * Returns the default value for the annotation member represented by
814      * this {@code Method} instance.  If the member is of a primitive type,
815      * an instance of the corresponding wrapper type is returned. Returns
816      * null if no default is associated with the member, or if the method
817      * instance does not represent a declared member of an annotation type.
818      *
819      * @return the default value for the annotation member represented
820      *     by this {@code Method} instance.
821      * @throws TypeNotPresentException if the annotation is of type
822      *     {@link Class} and no definition can be found for the
823      *     default class value.
824      * @since  1.5
825      * @jls 9.6.2 Defaults for Annotation Type Elements
826      */
827     public Object getDefaultValue() {
828         if  (annotationDefault == null)
829             return null;
830         Class<?> memberType = AnnotationType.invocationHandlerReturnType(
831             getReturnType());
832         Object result = AnnotationParser.parseMemberValue(
833             memberType, ByteBuffer.wrap(annotationDefault),
834             SharedSecrets.getJavaLangAccess().
835                 getConstantPool(getDeclaringClass()),
836             getDeclaringClass());
837         if (result instanceof ExceptionProxy) {
838             if (result instanceof TypeNotPresentExceptionProxy proxy) {
839                 throw new TypeNotPresentException(proxy.typeName(), proxy.getCause());
840             }
841             throw new AnnotationFormatError("Invalid default: " + this);
842         }
843         return result;
844     }
845 
846     /**
847      * {@inheritDoc}
848      * @throws NullPointerException {@inheritDoc}
849      * @since 1.5
850      */
851     @Override
852     public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
853         return super.getAnnotation(annotationClass);
854     }
855 
856     /**
857      * {@inheritDoc}
858      * @since 1.5
859      */
860     @Override
861     public Annotation[] getDeclaredAnnotations()  {
862         return super.getDeclaredAnnotations();
863     }
864 
865     /**
866      * {@inheritDoc}
867      * @since 1.5
868      */
869     @Override
870     public Annotation[][] getParameterAnnotations() {
871         return sharedGetParameterAnnotations(parameterTypes, parameterAnnotations);
872     }
873 
874     /**
875      * {@inheritDoc}
876      * @since 1.8
877      */
878     @Override
879     public AnnotatedType getAnnotatedReturnType() {
880         return getAnnotatedReturnType0(getGenericReturnType());
881     }
882 
883     @Override
884     boolean handleParameterNumberMismatch(int resultLength, Class<?>[] parameterTypes) {
885         throw new AnnotationFormatError("Parameter annotations don't match number of parameters");
886     }
887 }