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