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