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