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