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