1 /* 2 * Copyright (c) 1996, 2019, 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.HotSpotIntrinsicCandidate; 29 import jdk.internal.access.SharedSecrets; 30 import jdk.internal.reflect.CallerSensitive; 31 import jdk.internal.reflect.MethodAccessor; 32 import jdk.internal.reflect.Reflection; 33 import jdk.internal.vm.annotation.ForceInline; 34 import sun.reflect.annotation.ExceptionProxy; 35 import sun.reflect.annotation.TypeNotPresentExceptionProxy; 36 import sun.reflect.generics.repository.MethodRepository; 37 import sun.reflect.generics.factory.CoreReflectionFactory; 38 import sun.reflect.generics.factory.GenericsFactory; 39 import sun.reflect.generics.scope.MethodScope; 40 import sun.reflect.annotation.AnnotationType; 41 import sun.reflect.annotation.AnnotationParser; 42 import java.lang.annotation.Annotation; 43 import java.lang.annotation.AnnotationFormatError; 44 import java.nio.ByteBuffer; 45 import java.util.StringJoiner; 46 47 /** 48 * A {@code Method} provides information about, and access to, a single method 49 * on a class or interface. The reflected method may be a class method 50 * or an instance method (including an abstract method). 51 * 52 * <p>A {@code Method} permits widening conversions to occur when matching the 53 * actual parameters to invoke with the underlying method's formal 54 * parameters, but it throws an {@code IllegalArgumentException} if a 55 * narrowing conversion would occur. 56 * 57 * @see Member 58 * @see java.lang.Class 59 * @see java.lang.Class#getMethods() 60 * @see java.lang.Class#getMethod(String, Class[]) 61 * @see java.lang.Class#getDeclaredMethods() 62 * @see java.lang.Class#getDeclaredMethod(String, Class[]) 63 * 64 * @author Kenneth Russell 65 * @author Nakul Saraiya 66 * @since 1.1 67 */ 68 public final class Method extends Executable { 69 private Class<?> clazz; 70 private int slot; 71 // This is guaranteed to be interned by the VM in the 1.4 72 // reflection implementation 73 private String name; 74 private Class<?> returnType; 75 private Class<?>[] parameterTypes; 76 private Class<?>[] exceptionTypes; 77 private int modifiers; 78 // Generics and annotations support 79 private transient String signature; 80 // generic info repository; lazily initialized 81 private transient MethodRepository genericInfo; 82 private byte[] annotations; 83 private byte[] parameterAnnotations; 84 private byte[] annotationDefault; 85 private volatile MethodAccessor methodAccessor; 86 // For sharing of MethodAccessors. This branching structure is 87 // currently only two levels deep (i.e., one root Method and 88 // potentially many Method objects pointing to it.) 89 // 90 // If this branching structure would ever contain cycles, deadlocks can 91 // occur in annotation code. 92 private Method root; 93 94 // Generics infrastructure 95 private String getGenericSignature() {return signature;} 96 97 // Accessor for factory 98 private GenericsFactory getFactory() { 99 // create scope and factory 100 return CoreReflectionFactory.make(this, MethodScope.make(this)); 101 } 102 103 // Accessor for generic info repository 104 @Override 105 MethodRepository getGenericInfo() { 106 // lazily initialize repository if necessary 107 if (genericInfo == null) { 108 // create and cache generic info repository 109 genericInfo = MethodRepository.make(getGenericSignature(), 110 getFactory()); 111 } 112 return genericInfo; //return cached repository 113 } 114 115 /** 116 * Package-private constructor 117 */ 118 Method(Class<?> declaringClass, 119 String name, 120 Class<?>[] parameterTypes, 121 Class<?> returnType, 122 Class<?>[] checkedExceptions, 123 int modifiers, 124 int slot, 125 String signature, 126 byte[] annotations, 127 byte[] parameterAnnotations, 128 byte[] annotationDefault) { 129 this.clazz = declaringClass; 130 this.name = name; 131 this.parameterTypes = parameterTypes; 132 this.returnType = returnType; 133 this.exceptionTypes = checkedExceptions; 134 this.modifiers = modifiers; 135 this.slot = slot; 136 this.signature = signature; 137 this.annotations = annotations; 138 this.parameterAnnotations = parameterAnnotations; 139 this.annotationDefault = annotationDefault; 140 } 141 142 /** 143 * Package-private routine (exposed to java.lang.Class via 144 * ReflectAccess) which returns a copy of this Method. The copy's 145 * "root" field points to this Method. 146 */ 147 Method copy() { 148 // This routine enables sharing of MethodAccessor objects 149 // among Method objects which refer to the same underlying 150 // method in the VM. (All of this contortion is only necessary 151 // because of the "accessibility" bit in AccessibleObject, 152 // which implicitly requires that new java.lang.reflect 153 // objects be fabricated for each reflective call on Class 154 // objects.) 155 if (this.root != null) 156 throw new IllegalArgumentException("Can not copy a non-root Method"); 157 158 Method res = new Method(clazz, name, parameterTypes, returnType, 159 exceptionTypes, modifiers, slot, signature, 160 annotations, parameterAnnotations, annotationDefault); 161 res.root = this; 162 // Might as well eagerly propagate this if already present 163 res.methodAccessor = methodAccessor; 164 return res; 165 } 166 167 /** 168 * Make a copy of a leaf method. 169 */ 170 Method leafCopy() { 171 if (this.root == null) 172 throw new IllegalArgumentException("Can only leafCopy a non-root Method"); 173 174 Method res = new Method(clazz, name, parameterTypes, returnType, 175 exceptionTypes, modifiers, slot, signature, 176 annotations, parameterAnnotations, annotationDefault); 177 res.root = root; 178 res.methodAccessor = methodAccessor; 179 return res; 180 } 181 182 /** 183 * @throws InaccessibleObjectException {@inheritDoc} 184 * @throws SecurityException {@inheritDoc} 185 */ 186 @Override 187 @CallerSensitive 188 public void setAccessible(boolean flag) { 189 AccessibleObject.checkPermission(); 190 if (flag) checkCanSetAccessible(Reflection.getCallerClass()); 191 setAccessible0(flag); 192 } 193 194 @Override 195 void checkCanSetAccessible(Class<?> caller) { 196 checkCanSetAccessible(caller, clazz); 197 } 198 199 @Override 200 Method getRoot() { 201 return root; 202 } 203 204 @Override 205 boolean hasGenericInformation() { 206 return (getGenericSignature() != null); 207 } 208 209 @Override 210 byte[] getAnnotationBytes() { 211 return annotations; 212 } 213 214 /** 215 * Returns the {@code Class} object representing the class or interface 216 * that declares the method represented by this object. 217 */ 218 @Override 219 public Class<?> getDeclaringClass() { 220 return clazz; 221 } 222 223 /** 224 * Returns the name of the method represented by this {@code Method} 225 * object, as a {@code String}. 226 */ 227 @Override 228 public String getName() { 229 return name; 230 } 231 232 /** 233 * {@inheritDoc} 234 */ 235 @Override 236 public int getModifiers() { 237 return modifiers; 238 } 239 240 /** 241 * {@inheritDoc} 242 * @throws GenericSignatureFormatError {@inheritDoc} 243 * @since 1.5 244 */ 245 @Override 246 @SuppressWarnings({"rawtypes", "unchecked"}) 247 public TypeVariable<Method>[] getTypeParameters() { 248 if (getGenericSignature() != null) 249 return (TypeVariable<Method>[])getGenericInfo().getTypeParameters(); 250 else 251 return (TypeVariable<Method>[])new TypeVariable[0]; 252 } 253 254 /** 255 * Returns a {@code Class} object that represents the formal return type 256 * of the method represented by this {@code Method} object. 257 * 258 * @return the return type for the method this object represents 259 */ 260 public Class<?> getReturnType() { 261 return returnType; 262 } 263 264 /** 265 * Returns a {@code Type} object that represents the formal return 266 * type of the method represented by this {@code Method} object. 267 * 268 * <p>If the return type is a parameterized type, 269 * the {@code Type} object returned must accurately reflect 270 * the actual type arguments used in the source code. 271 * 272 * <p>If the return type is a type variable or a parameterized type, it 273 * is created. Otherwise, it is resolved. 274 * 275 * @return a {@code Type} object that represents the formal return 276 * type of the underlying method 277 * @throws GenericSignatureFormatError 278 * if the generic method signature does not conform to the format 279 * specified in 280 * <cite>The Java™ Virtual Machine Specification</cite> 281 * @throws TypeNotPresentException if the underlying method's 282 * return type refers to a non-existent type declaration 283 * @throws MalformedParameterizedTypeException if the 284 * underlying method's return typed refers to a parameterized 285 * type that cannot be instantiated for any reason 286 * @since 1.5 287 */ 288 public Type getGenericReturnType() { 289 if (getGenericSignature() != null) { 290 return getGenericInfo().getReturnType(); 291 } else { return getReturnType();} 292 } 293 294 @Override 295 Class<?>[] getSharedParameterTypes() { 296 return parameterTypes; 297 } 298 299 @Override 300 Class<?>[] getSharedExceptionTypes() { 301 return exceptionTypes; 302 } 303 304 /** 305 * {@inheritDoc} 306 */ 307 @Override 308 public Class<?>[] getParameterTypes() { 309 return parameterTypes.clone(); 310 } 311 312 /** 313 * {@inheritDoc} 314 * @since 1.8 315 */ 316 public int getParameterCount() { return parameterTypes.length; } 317 318 319 /** 320 * {@inheritDoc} 321 * @throws GenericSignatureFormatError {@inheritDoc} 322 * @throws TypeNotPresentException {@inheritDoc} 323 * @throws MalformedParameterizedTypeException {@inheritDoc} 324 * @since 1.5 325 */ 326 @Override 327 public Type[] getGenericParameterTypes() { 328 return super.getGenericParameterTypes(); 329 } 330 331 /** 332 * {@inheritDoc} 333 */ 334 @Override 335 public Class<?>[] getExceptionTypes() { 336 return exceptionTypes.clone(); 337 } 338 339 /** 340 * {@inheritDoc} 341 * @throws GenericSignatureFormatError {@inheritDoc} 342 * @throws TypeNotPresentException {@inheritDoc} 343 * @throws MalformedParameterizedTypeException {@inheritDoc} 344 * @since 1.5 345 */ 346 @Override 347 public Type[] getGenericExceptionTypes() { 348 return super.getGenericExceptionTypes(); 349 } 350 351 /** 352 * Compares this {@code Method} against the specified object. Returns 353 * true if the objects are the same. Two {@code Methods} are the same if 354 * they were declared by the same class and have the same name 355 * and formal parameter types and return type. 356 */ 357 public boolean equals(Object obj) { 358 if (obj != null && obj instanceof Method) { 359 Method other = (Method)obj; 360 if ((getDeclaringClass() == other.getDeclaringClass()) 361 && (getName() == other.getName())) { 362 if (!returnType.equals(other.getReturnType())) 363 return false; 364 return equalParamTypes(parameterTypes, other.parameterTypes); 365 } 366 } 367 return false; 368 } 369 370 /** 371 * Returns a hashcode for this {@code Method}. The hashcode is computed 372 * as the exclusive-or of the hashcodes for the underlying 373 * method's declaring class name and the method's name. 374 */ 375 public int hashCode() { 376 return getDeclaringClass().getName().hashCode() ^ getName().hashCode(); 377 } 378 379 /** 380 * Returns a string describing this {@code Method}. The string is 381 * formatted as the method access modifiers, if any, followed by 382 * the method return type, followed by a space, followed by the 383 * class declaring the method, followed by a period, followed by 384 * the method name, followed by a parenthesized, comma-separated 385 * list of the method's formal parameter types. If the method 386 * throws checked exceptions, the parameter list is followed by a 387 * space, followed by the word "{@code throws}" followed by a 388 * comma-separated list of the thrown exception types. 389 * For example: 390 * <pre> 391 * public boolean java.lang.Object.equals(java.lang.Object) 392 * </pre> 393 * 394 * <p>The access modifiers are placed in canonical order as 395 * specified by "The Java Language Specification". This is 396 * {@code public}, {@code protected} or {@code private} first, 397 * and then other modifiers in the following order: 398 * {@code abstract}, {@code default}, {@code static}, {@code final}, 399 * {@code synchronized}, {@code native}, {@code strictfp}. 400 * 401 * @return a string describing this {@code Method} 402 * 403 * @jls 8.4.3 Method Modifiers 404 * @jls 9.4 Method Declarations 405 * @jls 9.6.1 Annotation Type Elements 406 */ 407 public String toString() { 408 return sharedToString(Modifier.methodModifiers(), 409 isDefault(), 410 parameterTypes, 411 exceptionTypes); 412 } 413 414 @Override 415 void specificToStringHeader(StringBuilder sb) { 416 sb.append(getReturnType().getTypeName()).append(' '); 417 sb.append(getDeclaringClass().getTypeName()).append('.'); 418 sb.append(getName()); 419 } 420 421 @Override 422 String toShortString() { 423 StringBuilder sb = new StringBuilder("method "); 424 sb.append(getDeclaringClass().getTypeName()).append('.'); 425 sb.append(getName()); 426 sb.append('('); 427 StringJoiner sj = new StringJoiner(","); 428 for (Class<?> parameterType : getParameterTypes()) { 429 sj.add(parameterType.getTypeName()); 430 } 431 sb.append(sj); 432 sb.append(')'); 433 return sb.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 Type 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 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 * @exception IllegalAccessException if this {@code Method} object 529 * is enforcing Java language access control and the underlying 530 * method is inaccessible. 531 * @exception 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 * @exception InvocationTargetException if the underlying method 542 * throws an exception. 543 * @exception NullPointerException if the specified object is null 544 * and the method is an instance method. 545 * @exception ExceptionInInitializerError if the initialization 546 * provoked by this method fails. 547 */ 548 @CallerSensitive 549 @ForceInline // to ensure Reflection.getCallerClass optimization 550 @HotSpotIntrinsicCandidate 551 public Object invoke(Object obj, Object... args) 552 throws IllegalAccessException, IllegalArgumentException, 553 InvocationTargetException 554 { 555 if (!override) { 556 Class<?> caller = Reflection.getCallerClass(); 557 checkAccess(caller, clazz, 558 Modifier.isStatic(modifiers) ? null : obj.getClass(), 559 modifiers); 560 } 561 MethodAccessor ma = methodAccessor; // read volatile 562 if (ma == null) { 563 ma = acquireMethodAccessor(); 564 } 565 return ma.invoke(obj, args); 566 } 567 568 /** 569 * Returns {@code true} if this method is a bridge 570 * method; returns {@code false} otherwise. 571 * 572 * @return true if and only if this method is a bridge 573 * method as defined by the Java Language Specification. 574 * @since 1.5 575 */ 576 public boolean isBridge() { 577 return (getModifiers() & Modifier.BRIDGE) != 0; 578 } 579 580 /** 581 * {@inheritDoc} 582 * @since 1.5 583 */ 584 @Override 585 public boolean isVarArgs() { 586 return super.isVarArgs(); 587 } 588 589 /** 590 * {@inheritDoc} 591 * @jls 13.1 The Form of a Binary 592 * @since 1.5 593 */ 594 @Override 595 public boolean isSynthetic() { 596 return super.isSynthetic(); 597 } 598 599 /** 600 * Returns {@code true} if this method is a default 601 * method; returns {@code false} otherwise. 602 * 603 * A default method is a public non-abstract instance method, that 604 * is, a non-static method with a body, declared in an interface 605 * type. 606 * 607 * @return true if and only if this method is a default 608 * method as defined by the Java Language Specification. 609 * @since 1.8 610 */ 611 public boolean isDefault() { 612 // Default methods are public non-abstract instance methods 613 // declared in an interface. 614 return ((getModifiers() & (Modifier.ABSTRACT | Modifier.PUBLIC | Modifier.STATIC)) == 615 Modifier.PUBLIC) && getDeclaringClass().isInterface(); 616 } 617 618 // NOTE that there is no synchronization used here. It is correct 619 // (though not efficient) to generate more than one MethodAccessor 620 // for a given Method. However, avoiding synchronization will 621 // probably make the implementation more scalable. 622 private MethodAccessor acquireMethodAccessor() { 623 // First check to see if one has been created yet, and take it 624 // if so 625 MethodAccessor tmp = null; 626 if (root != null) tmp = root.getMethodAccessor(); 627 if (tmp != null) { 628 methodAccessor = tmp; 629 } else { 630 // Otherwise fabricate one and propagate it up to the root 631 tmp = reflectionFactory.newMethodAccessor(this); 632 setMethodAccessor(tmp); 633 } 634 635 return tmp; 636 } 637 638 // Returns MethodAccessor for this Method object, not looking up 639 // the chain to the root 640 MethodAccessor getMethodAccessor() { 641 return methodAccessor; 642 } 643 644 // Sets the MethodAccessor for this Method object and 645 // (recursively) its root 646 void setMethodAccessor(MethodAccessor accessor) { 647 methodAccessor = accessor; 648 // Propagate up 649 if (root != null) { 650 root.setMethodAccessor(accessor); 651 } 652 } 653 654 /** 655 * Returns the default value for the annotation member represented by 656 * this {@code Method} instance. If the member is of a primitive type, 657 * an instance of the corresponding wrapper type is returned. Returns 658 * null if no default is associated with the member, or if the method 659 * instance does not represent a declared member of an annotation type. 660 * 661 * @return the default value for the annotation member represented 662 * by this {@code Method} instance. 663 * @throws TypeNotPresentException if the annotation is of type 664 * {@link Class} and no definition can be found for the 665 * default class value. 666 * @since 1.5 667 */ 668 public Object getDefaultValue() { 669 if (annotationDefault == null) 670 return null; 671 Class<?> memberType = AnnotationType.invocationHandlerReturnType( 672 getReturnType()); 673 Object result = AnnotationParser.parseMemberValue( 674 memberType, ByteBuffer.wrap(annotationDefault), 675 SharedSecrets.getJavaLangAccess(). 676 getConstantPool(getDeclaringClass()), 677 getDeclaringClass()); 678 if (result instanceof ExceptionProxy) { 679 if (result instanceof TypeNotPresentExceptionProxy) { 680 TypeNotPresentExceptionProxy proxy = (TypeNotPresentExceptionProxy)result; 681 throw new TypeNotPresentException(proxy.typeName(), proxy.getCause()); 682 } 683 throw new AnnotationFormatError("Invalid default: " + this); 684 } 685 return result; 686 } 687 688 /** 689 * {@inheritDoc} 690 * @throws NullPointerException {@inheritDoc} 691 * @since 1.5 692 */ 693 public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { 694 return super.getAnnotation(annotationClass); 695 } 696 697 /** 698 * {@inheritDoc} 699 * @since 1.5 700 */ 701 public Annotation[] getDeclaredAnnotations() { 702 return super.getDeclaredAnnotations(); 703 } 704 705 /** 706 * {@inheritDoc} 707 * @since 1.5 708 */ 709 @Override 710 public Annotation[][] getParameterAnnotations() { 711 return sharedGetParameterAnnotations(parameterTypes, parameterAnnotations); 712 } 713 714 /** 715 * {@inheritDoc} 716 * @since 1.8 717 */ 718 @Override 719 public AnnotatedType getAnnotatedReturnType() { 720 return getAnnotatedReturnType0(getGenericReturnType()); 721 } 722 723 @Override 724 boolean handleParameterNumberMismatch(int resultLength, int numParameters) { 725 throw new AnnotationFormatError("Parameter annotations don't match number of parameters"); 726 } 727 }