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.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(parameterTypes,
424 exceptionTypes);
425 }
426
427 @Override
428 void appendModifiers(StringBuilder sb) {
429 int mods = getModifiers();
430 Reflection.appendAccessControlModifiers(sb, mods);
431 if (Modifier.isAbstract(mods))
432 sb.append("abstract ");
433 if (isDefault())
434 sb.append("default ");
435 if (Modifier.isStatic(mods))
436 sb.append("static ");
437 if (Modifier.isFinal(mods))
438 sb.append("final ");
439 if (Modifier.isSynchronized(mods))
440 sb.append("synchronized ");
441 if (Modifier.isNative(mods))
442 sb.append("native ");
443 if (Modifier.isStrict(mods))
444 sb.append("strictfp ");
445 }
446
447 @Override
448 void specificToStringHeader(StringBuilder sb) {
449 sb.append(getReturnType().getTypeName()).append(' ');
450 sb.append(getDeclaringClass().getTypeName()).append('.');
451 sb.append(getName());
452 }
453
454 @Override
455 String toShortString() {
456 return "method " + getDeclaringClass().getTypeName() +
457 '.' + toShortSignature();
458 }
459
460 String toShortSignature() {
461 StringJoiner sj = new StringJoiner(",", getName() + "(", ")");
462 for (Class<?> parameterType : getSharedParameterTypes()) {
463 sj.add(parameterType.getTypeName());
464 }
465 return sj.toString();
466 }
467
468 /**
469 * Returns a string describing this {@code Method}, including type
470 * parameters. The string is formatted as the method access
471 * modifiers, if any, followed by an angle-bracketed
472 * comma-separated list of the method's type parameters, if any,
473 * including informative bounds of the type parameters, if any,
474 * followed by the method's generic return type, followed by a
475 * space, followed by the class declaring the method, followed by
476 * a period, followed by the method name, followed by a
477 * parenthesized, comma-separated list of the method's generic
478 * formal parameter types.
479 *
480 * If this method was declared to take a variable number of
481 * arguments, instead of denoting the last parameter as
482 * "<code><i>Type</i>[]</code>", it is denoted as
483 * "<code><i>Type</i>...</code>".
484 *
485 * A space is used to separate access modifiers from one another
486 * and from the type parameters or return type. If there are no
487 * type parameters, the type parameter list is elided; if the type
488 * parameter list is present, a space separates the list from the
489 * class name. If the method is declared to throw exceptions, the
490 * parameter list is followed by a space, followed by the word
491 * "{@code throws}" followed by a comma-separated list of the generic
492 * thrown exception types.
493 *
494 * <p>The access modifiers are placed in canonical order as
495 * specified by "The Java Language Specification". This is
496 * {@code public}, {@code protected} or {@code private} first,
497 * and then other modifiers in the following order:
498 * {@code abstract}, {@code default}, {@code static}, {@code final},
499 * {@code synchronized}, {@code native}, {@code strictfp}.
500 *
501 * @return a string describing this {@code Method},
502 * include type parameters
503 *
504 * @since 1.5
505 *
506 * @jls 8.4.3 Method Modifiers
507 * @jls 9.4 Method Declarations
508 * @jls 9.6.1 Annotation Interface Elements
509 */
510 @Override
511 public String toGenericString() {
512 return super.toGenericString();
513 }
514
515 @Override
516 void specificToGenericStringHeader(StringBuilder sb) {
517 Type genRetType = getGenericReturnType();
518 sb.append(genRetType.getTypeName()).append(' ');
519 sb.append(getDeclaringClass().getTypeName()).append('.');
520 sb.append(getName());
521 }
522
523 /**
524 * Invokes the underlying method represented by this {@code Method}
525 * object, on the specified object with the specified parameters.
526 * Individual parameters are automatically unwrapped to match
527 * primitive formal parameters, and both primitive and reference
528 * parameters are subject to method invocation conversions as
529 * necessary.
530 *
531 * <p>If the underlying method is static, then the specified {@code obj}
532 * argument is ignored. It may be null.
533 *
534 * <p>If the number of formal parameters required by the underlying method is
535 * 0, the supplied {@code args} array may be of length 0 or null.
536 *
537 * <p>If the underlying method is an instance method, it is invoked
538 * using dynamic method lookup as documented in The Java Language
539 * Specification, section {@jls 15.12.4.4}; in particular,
540 * overriding based on the runtime type of the target object may occur.
541 *
542 * <p>If the underlying method is static, the class that declared
543 * the method is initialized if it has not already been initialized.
544 *
545 * <p>If the method completes normally, the value it returns is
546 * returned to the caller of invoke; if the value has a primitive
547 * type, it is first appropriately wrapped in an object. However,
548 * if the value has the type of an array of a primitive type, the
549 * elements of the array are <i>not</i> wrapped in objects; in
550 * other words, an array of primitive type is returned. If the
551 * underlying method return type is void, the invocation returns
552 * null.
553 *
554 * @param obj the object the underlying method is invoked from
555 * @param args the arguments used for the method call
556 * @return the result of dispatching the method represented by
557 * this object on {@code obj} with parameters
558 * {@code args}
559 *
560 * @throws IllegalAccessException if this {@code Method} object
561 * is enforcing Java language access control and the underlying
562 * method is inaccessible.
563 * @throws IllegalArgumentException if the method is an
564 * instance method and the specified object argument
565 * is not an instance of the class or interface
566 * declaring the underlying method (or of a subclass
567 * or implementor thereof); if the number of actual
568 * and formal parameters differ; if an unwrapping
569 * conversion for primitive arguments fails; or if,
570 * after possible unwrapping, a parameter value
571 * cannot be converted to the corresponding formal
572 * parameter type by a method invocation conversion.
573 * @throws InvocationTargetException if the underlying method
574 * throws an exception.
575 * @throws NullPointerException if the specified object is null
576 * and the method is an instance method.
577 * @throws ExceptionInInitializerError if the initialization
578 * provoked by this method fails.
579 */
580 @CallerSensitive
581 @ForceInline // to ensure Reflection.getCallerClass optimization
582 @IntrinsicCandidate
583 public Object invoke(Object obj, Object... args)
584 throws IllegalAccessException, InvocationTargetException
585 {
586 boolean callerSensitive = isCallerSensitive();
587 Class<?> caller = null;
588 if (!override || callerSensitive) {
589 caller = Reflection.getCallerClass();
590 }
591
592 // Reflection::getCallerClass filters all subclasses of
593 // jdk.internal.reflect.MethodAccessorImpl and Method::invoke(Object, Object[])
594 // Should not call Method::invoke(Object, Object[], Class) here
595 if (!override) {
596 checkAccess(caller, clazz,
597 Modifier.isStatic(modifiers) ? null : obj.getClass(),
598 modifiers);
599 }
600 MethodAccessor ma = methodAccessor; // read @Stable
601 if (ma == null) {
602 ma = acquireMethodAccessor();
603 }
604
605 return callerSensitive ? ma.invoke(obj, args, caller) : ma.invoke(obj, args);
606 }
607
608 /**
609 * This is to support MethodHandle calling caller-sensitive Method::invoke
610 * that may invoke a caller-sensitive method in order to get the original caller
611 * class (not the injected invoker).
612 *
613 * If this adapter is not presented, MethodHandle invoking Method::invoke
614 * will get an invoker class, a hidden nestmate of the original caller class,
615 * that becomes the caller class invoking Method::invoke.
616 */
617 @CallerSensitiveAdapter
618 private Object invoke(Object obj, Object[] args, Class<?> caller)
619 throws IllegalAccessException, InvocationTargetException
620 {
621 boolean callerSensitive = isCallerSensitive();
622 if (!override) {
623 checkAccess(caller, clazz,
624 Modifier.isStatic(modifiers) ? null : obj.getClass(),
625 modifiers);
626 }
627 MethodAccessor ma = methodAccessor; // read @Stable
628 if (ma == null) {
629 ma = acquireMethodAccessor();
630 }
631
632 return callerSensitive ? ma.invoke(obj, args, caller) : ma.invoke(obj, args);
633 }
634
635 // 0 = not initialized (@Stable contract)
636 // 1 = initialized, CS
637 // -1 = initialized, not CS
638 @Stable private byte callerSensitive;
639
640 private boolean isCallerSensitive() {
641 byte cs = callerSensitive;
642 if (cs == 0) {
643 callerSensitive = cs = (byte)(Reflection.isCallerSensitive(this) ? 1 : -1);
644 }
645 return (cs > 0);
646 }
647
648 /**
649 * {@return {@code true} if this method is a bridge
650 * method; returns {@code false} otherwise}
651 *
652 * @apiNote
653 * A bridge method is a {@linkplain isSynthetic synthetic} method
654 * created by a Java compiler alongside a method originating from
655 * the source code. Bridge methods are used by Java compilers in
656 * various circumstances to span differences in Java programming
657 * language semantics and JVM semantics.
658 *
659 * <p>One example use of bridge methods is as a technique for a
660 * Java compiler to support <i>covariant overrides</i>, where a
661 * subclass overrides a method and gives the new method a more
662 * specific return type than the method in the superclass. While
663 * the Java language specification forbids a class declaring two
664 * methods with the same parameter types but a different return
665 * type, the virtual machine does not. A common case where
666 * covariant overrides are used is for a {@link
667 * java.lang.Cloneable Cloneable} class where the {@link
668 * Object#clone() clone} method inherited from {@code
669 * java.lang.Object} is overridden and declared to return the type
670 * of the class. For example, {@code Object} declares
671 * <pre>{@code protected Object clone() throws CloneNotSupportedException {...}}</pre>
672 * and {@code EnumSet<E>} declares its language-level {@linkplain
673 * java.util.EnumSet#clone() covariant override}
674 * <pre>{@code public EnumSet<E> clone() {...}}</pre>
675 * If this technique was being used, the resulting class file for
676 * {@code EnumSet} would have two {@code clone} methods, one
677 * returning {@code EnumSet<E>} and the second a bridge method
678 * returning {@code Object}. The bridge method is a JVM-level
679 * override of {@code Object.clone()}. The body of the {@code
680 * clone} bridge method calls its non-bridge counterpart and
681 * returns its result.
682 * @since 1.5
683 *
684 * @jls 8.4.8.3 Requirements in Overriding and Hiding
685 * @jls 15.12.4.5 Create Frame, Synchronize, Transfer Control
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 */
691 public boolean isBridge() {
692 return (getModifiers() & Modifier.BRIDGE) != 0;
693 }
694
695 /**
696 * {@inheritDoc}
697 * @since 1.5
698 * @jls 8.4.1 Formal Parameters
699 */
700 @Override
701 public boolean isVarArgs() {
702 return super.isVarArgs();
703 }
704
705 /**
706 * {@inheritDoc}
707 * @jls 13.1 The Form of a Binary
708 * @jvms 4.6 Methods
709 * @see <a
710 * href="{@docRoot}/java.base/java/lang/reflect/package-summary.html#LanguageJvmModel">Java
711 * programming language and JVM modeling in core reflection</a>
712 * @since 1.5
713 */
714 @Override
715 public boolean isSynthetic() {
716 return super.isSynthetic();
717 }
718
719 /**
720 * Returns {@code true} if this method is a default
721 * method; returns {@code false} otherwise.
722 *
723 * A default method is a public non-abstract instance method, that
724 * is, a non-static method with a body, declared in an interface.
725 *
726 * @return true if and only if this method is a default
727 * method as defined by the Java Language Specification.
728 * @since 1.8
729 * @jls 9.4 Method Declarations
730 */
731 public boolean isDefault() {
732 // Default methods are public non-abstract instance methods
733 // declared in an interface.
734 return ((getModifiers() & (Modifier.ABSTRACT | Modifier.PUBLIC | Modifier.STATIC)) ==
735 Modifier.PUBLIC) && getDeclaringClass().isInterface();
736 }
737
738 // NOTE that there is no synchronization used here. It is correct
739 // (though not efficient) to generate more than one MethodAccessor
740 // for a given Method. However, avoiding synchronization will
741 // probably make the implementation more scalable.
742 private MethodAccessor acquireMethodAccessor() {
743 // First check to see if one has been created yet, and take it
744 // if so
745 Method root = this.root;
746 MethodAccessor tmp = root == null ? null : root.getMethodAccessor();
747 if (tmp != null) {
748 methodAccessor = tmp;
749 } else {
750 // Otherwise fabricate one and propagate it up to the root
751 tmp = reflectionFactory.newMethodAccessor(this, isCallerSensitive());
752 // set the method accessor only if it's not using native implementation
753 if (VM.isJavaLangInvokeInited())
754 setMethodAccessor(tmp);
755 }
756
757 return tmp;
758 }
759
760 // Returns MethodAccessor for this Method object, not looking up
761 // the chain to the root
762 MethodAccessor getMethodAccessor() {
763 return methodAccessor;
764 }
765
766 // Sets the MethodAccessor for this Method object and
767 // (recursively) its root
768 void setMethodAccessor(MethodAccessor accessor) {
769 methodAccessor = accessor;
770 // Propagate up
771 Method root = this.root;
772 if (root != null) {
773 root.setMethodAccessor(accessor);
774 }
775 }
776
777 /**
778 * Returns the default value for the annotation member represented by
779 * this {@code Method} instance. If the member is of a primitive type,
780 * an instance of the corresponding wrapper type is returned. Returns
781 * null if no default is associated with the member, or if the method
782 * instance does not represent a declared member of an annotation type.
783 *
784 * @return the default value for the annotation member represented
785 * by this {@code Method} instance.
786 * @throws TypeNotPresentException if the annotation is of type
787 * {@link Class} and no definition can be found for the
788 * default class value.
789 * @since 1.5
790 * @jls 9.6.2 Defaults for Annotation Interface Elements
791 */
792 public Object getDefaultValue() {
793 if (annotationDefault == null)
794 return null;
795 Class<?> memberType = AnnotationType.invocationHandlerReturnType(
796 getReturnType());
797 Object result = AnnotationParser.parseMemberValue(
798 memberType, ByteBuffer.wrap(annotationDefault),
799 SharedSecrets.getJavaLangAccess().
800 getConstantPool(getDeclaringClass()),
801 getDeclaringClass());
802 if (result instanceof ExceptionProxy) {
803 if (result instanceof TypeNotPresentExceptionProxy proxy) {
804 throw new TypeNotPresentException(proxy.typeName(), proxy.getCause());
805 }
806 throw new AnnotationFormatError("Invalid default: " + this);
807 }
808 return result;
809 }
810
811 /**
812 * {@inheritDoc}
813 * @throws NullPointerException {@inheritDoc}
814 * @since 1.5
815 */
816 @Override
817 public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
818 return super.getAnnotation(annotationClass);
819 }
820
821 /**
822 * {@inheritDoc}
823 * @since 1.5
824 */
825 @Override
826 public Annotation[] getDeclaredAnnotations() {
827 return super.getDeclaredAnnotations();
828 }
829
830 /**
831 * {@inheritDoc}
832 * @since 1.5
833 */
834 @Override
835 public Annotation[][] getParameterAnnotations() {
836 return sharedGetParameterAnnotations(parameterTypes, parameterAnnotations);
837 }
838
839 /**
840 * {@inheritDoc}
841 * @since 1.8
842 */
843 @Override
844 public AnnotatedType getAnnotatedReturnType() {
845 return getAnnotatedReturnType0(getGenericReturnType());
846 }
847
848 @Override
849 boolean handleParameterNumberMismatch(int resultLength, Class<?>[] parameterTypes) {
850 throw new AnnotationFormatError("Parameter annotations don't match number of parameters");
851 }
852 }