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