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