1 /* 2 * Copyright (c) 1996, 2016, 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.misc.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 46 /** 47 * A {@code Method} provides information about, and access to, a single method 48 * on a class or interface. The reflected method may be a class method 49 * or an instance method (including an abstract method). 50 * 51 * <p>A {@code Method} permits widening conversions to occur when matching the 52 * actual parameters to invoke with the underlying method's formal 53 * parameters, but it throws an {@code IllegalArgumentException} if a 54 * narrowing conversion would occur. 55 * 56 * @see Member 57 * @see java.lang.Class 58 * @see java.lang.Class#getMethods() 59 * @see java.lang.Class#getMethod(String, Class[]) 60 * @see java.lang.Class#getDeclaredMethods() 61 * @see java.lang.Class#getDeclaredMethod(String, Class[]) 62 * 63 * @author Kenneth Russell 64 * @author Nakul Saraiya 65 */ 66 public final class Method extends Executable { 67 private Class<?> clazz; 68 private int slot; 69 // This is guaranteed to be interned by the VM in the 1.4 70 // reflection implementation 71 private String name; 72 private Class<?> returnType; 73 private Class<?>[] parameterTypes; 74 private Class<?>[] exceptionTypes; 75 private int modifiers; 76 // Generics and annotations support 77 private transient String signature; 78 // generic info repository; lazily initialized 79 private transient MethodRepository genericInfo; 80 private byte[] annotations; 81 private byte[] parameterAnnotations; 82 private byte[] annotationDefault; 83 private volatile MethodAccessor methodAccessor; 84 // For sharing of MethodAccessors. This branching structure is 85 // currently only two levels deep (i.e., one root Method and 86 // potentially many Method objects pointing to it.) 87 // 88 // If this branching structure would ever contain cycles, deadlocks can 89 // occur in annotation code. 90 private Method root; 91 92 // Generics infrastructure 93 private String getGenericSignature() {return signature;} 94 95 // Accessor for factory 96 private GenericsFactory getFactory() { 97 // create scope and factory 98 return CoreReflectionFactory.make(this, MethodScope.make(this)); 99 } 100 101 // Accessor for generic info repository 102 @Override 103 MethodRepository getGenericInfo() { 104 // lazily initialize repository if necessary 105 if (genericInfo == null) { 106 // create and cache generic info repository 107 genericInfo = MethodRepository.make(getGenericSignature(), 108 getFactory()); 109 } 110 return genericInfo; //return cached repository 111 } 112 113 /** 114 * Package-private constructor used by ReflectAccess to enable 115 * instantiation of these objects in Java code from the java.lang 116 * package via sun.reflect.LangReflectAccess. 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 * @since 9 186 */ 187 @Override 188 @CallerSensitive 189 public void setAccessible(boolean flag) { 190 AccessibleObject.checkPermission(); 191 if (flag) checkCanSetAccessible(Reflection.getCallerClass()); 192 setAccessible0(flag); 193 } 194 195 @Override 196 void checkCanSetAccessible(Class<?> caller) { 197 checkCanSetAccessible(caller, clazz); 198 } 199 200 /** 201 * Used by Excecutable for annotation sharing. 202 */ 203 @Override 204 Executable getRoot() { 205 return root; 206 } 207 208 @Override 209 boolean hasGenericInformation() { 210 return (getGenericSignature() != null); 211 } 212 213 @Override 214 byte[] getAnnotationBytes() { 215 return annotations; 216 } 217 218 /** 219 * Returns the {@code Class} object representing the class or interface 220 * that declares the method represented by this object. 221 */ 222 @Override 223 public Class<?> getDeclaringClass() { 224 return clazz; 225 } 226 227 /** 228 * Returns the name of the method represented by this {@code Method} 229 * object, as a {@code String}. 230 */ 231 @Override 232 public String getName() { 233 return name; 234 } 235 236 /** 237 * {@inheritDoc} 238 */ 239 @Override 240 public int getModifiers() { 241 return modifiers; 242 } 243 244 /** 245 * {@inheritDoc} 246 * @throws GenericSignatureFormatError {@inheritDoc} 247 * @since 1.5 248 */ 249 @Override 250 @SuppressWarnings({"rawtypes", "unchecked"}) 251 public TypeVariable<Method>[] getTypeParameters() { 252 if (getGenericSignature() != null) 253 return (TypeVariable<Method>[])getGenericInfo().getTypeParameters(); 254 else 255 return (TypeVariable<Method>[])new TypeVariable[0]; 256 } 257 258 /** 259 * Returns a {@code Class} object that represents the formal return type 260 * of the method represented by this {@code Method} object. 261 * 262 * @return the return type for the method this object represents 263 */ 264 public Class<?> getReturnType() { 265 return returnType; 266 } 267 268 /** 269 * Returns a {@code Type} object that represents the formal return 270 * type of the method represented by this {@code Method} object. 271 * 272 * <p>If the return type is a parameterized type, 273 * the {@code Type} object returned must accurately reflect 274 * the actual type parameters used in the source code. 275 * 276 * <p>If the return type is a type variable or a parameterized type, it 277 * is created. Otherwise, it is resolved. 278 * 279 * @return a {@code Type} object that represents the formal return 280 * type of the underlying method 281 * @throws GenericSignatureFormatError 282 * if the generic method signature does not conform to the format 283 * specified in 284 * <cite>The Java™ Virtual Machine Specification</cite> 285 * @throws TypeNotPresentException if the underlying method's 286 * return type refers to a non-existent type declaration 287 * @throws MalformedParameterizedTypeException if the 288 * underlying method's return typed refers to a parameterized 289 * type that cannot be instantiated for any reason 290 * @since 1.5 291 */ 292 public Type getGenericReturnType() { 293 if (getGenericSignature() != null) { 294 return getGenericInfo().getReturnType(); 295 } else { return getReturnType();} 296 } 297 298 @Override 299 Class<?>[] getSharedParameterTypes() { 300 return parameterTypes; 301 } 302 303 /** 304 * {@inheritDoc} 305 */ 306 @Override 307 public Class<?>[] getParameterTypes() { 308 return parameterTypes.clone(); 309 } 310 311 /** 312 * {@inheritDoc} 313 * @since 1.8 314 */ 315 public int getParameterCount() { return parameterTypes.length; } 316 317 318 /** 319 * {@inheritDoc} 320 * @throws GenericSignatureFormatError {@inheritDoc} 321 * @throws TypeNotPresentException {@inheritDoc} 322 * @throws MalformedParameterizedTypeException {@inheritDoc} 323 * @since 1.5 324 */ 325 @Override 326 public Type[] getGenericParameterTypes() { 327 return super.getGenericParameterTypes(); 328 } 329 330 /** 331 * {@inheritDoc} 332 */ 333 @Override 334 public Class<?>[] getExceptionTypes() { 335 return exceptionTypes.clone(); 336 } 337 338 /** 339 * {@inheritDoc} 340 * @throws GenericSignatureFormatError {@inheritDoc} 341 * @throws TypeNotPresentException {@inheritDoc} 342 * @throws MalformedParameterizedTypeException {@inheritDoc} 343 * @since 1.5 344 */ 345 @Override 346 public Type[] getGenericExceptionTypes() { 347 return super.getGenericExceptionTypes(); 348 } 349 350 /** 351 * Compares this {@code Method} against the specified object. Returns 352 * true if the objects are the same. Two {@code Methods} are the same if 353 * they were declared by the same class and have the same name 354 * and formal parameter types and return type. 355 */ 356 public boolean equals(Object obj) { 357 if (obj != null && obj instanceof Method) { 358 Method other = (Method)obj; 359 if ((getDeclaringClass() == other.getDeclaringClass()) 360 && (getName() == other.getName())) { 361 if (!returnType.equals(other.getReturnType())) 362 return false; 363 return equalParamTypes(parameterTypes, other.parameterTypes); 364 } 365 } 366 return false; 367 } 368 369 /** 370 * Returns a hashcode for this {@code Method}. The hashcode is computed 371 * as the exclusive-or of the hashcodes for the underlying 372 * method's declaring class name and the method's name. 373 */ 374 public int hashCode() { 375 return getDeclaringClass().getName().hashCode() ^ getName().hashCode(); 376 } 377 378 /** 379 * Returns a string describing this {@code Method}. The string is 380 * formatted as the method access modifiers, if any, followed by 381 * the method return type, followed by a space, followed by the 382 * class declaring the method, followed by a period, followed by 383 * the method name, followed by a parenthesized, comma-separated 384 * list of the method's formal parameter types. If the method 385 * throws checked exceptions, the parameter list is followed by a 386 * space, followed by the word "{@code throws}" followed by a 387 * comma-separated list of the thrown exception types. 388 * For example: 389 * <pre> 390 * public boolean java.lang.Object.equals(java.lang.Object) 391 * </pre> 392 * 393 * <p>The access modifiers are placed in canonical order as 394 * specified by "The Java Language Specification". This is 395 * {@code public}, {@code protected} or {@code private} first, 396 * and then other modifiers in the following order: 397 * {@code abstract}, {@code default}, {@code static}, {@code final}, 398 * {@code synchronized}, {@code native}, {@code strictfp}. 399 * 400 * @return a string describing this {@code Method} 401 * 402 * @jls 8.4.3 Method Modifiers 403 * @jls 9.4 Method Declarations 404 * @jls 9.6.1 Annotation Type Elements 405 */ 406 public String toString() { 407 return sharedToString(Modifier.methodModifiers(), 408 isDefault(), 409 parameterTypes, 410 exceptionTypes); 411 } 412 413 @Override 414 void specificToStringHeader(StringBuilder sb) { 415 sb.append(getReturnType().getTypeName()).append(' '); 416 sb.append(getDeclaringClass().getTypeName()).append('.'); 417 sb.append(getName()); 418 } 419 420 /** 421 * Returns a string describing this {@code Method}, including 422 * type parameters. The string is formatted as the method access 423 * modifiers, if any, followed by an angle-bracketed 424 * comma-separated list of the method's type parameters, if any, 425 * followed by the method's generic return type, followed by a 426 * space, followed by the class declaring the method, followed by 427 * a period, followed by the method name, followed by a 428 * parenthesized, comma-separated list of the method's generic 429 * formal parameter types. 430 * 431 * If this method was declared to take a variable number of 432 * arguments, instead of denoting the last parameter as 433 * "<code><i>Type</i>[]</code>", it is denoted as 434 * "<code><i>Type</i>...</code>". 435 * 436 * A space is used to separate access modifiers from one another 437 * and from the type parameters or return type. If there are no 438 * type parameters, the type parameter list is elided; if the type 439 * parameter list is present, a space separates the list from the 440 * class name. If the method is declared to throw exceptions, the 441 * parameter list is followed by a space, followed by the word 442 * "{@code throws}" followed by a comma-separated list of the generic 443 * thrown exception types. 444 * 445 * <p>The access modifiers are placed in canonical order as 446 * specified by "The Java Language Specification". This is 447 * {@code public}, {@code protected} or {@code private} first, 448 * and then other modifiers in the following order: 449 * {@code abstract}, {@code default}, {@code static}, {@code final}, 450 * {@code synchronized}, {@code native}, {@code strictfp}. 451 * 452 * @return a string describing this {@code Method}, 453 * include type parameters 454 * 455 * @since 1.5 456 * 457 * @jls 8.4.3 Method Modifiers 458 * @jls 9.4 Method Declarations 459 * @jls 9.6.1 Annotation Type Elements 460 */ 461 @Override 462 public String toGenericString() { 463 return sharedToGenericString(Modifier.methodModifiers(), isDefault()); 464 } 465 466 @Override 467 void specificToGenericStringHeader(StringBuilder sb) { 468 Type genRetType = getGenericReturnType(); 469 sb.append(genRetType.getTypeName()).append(' '); 470 sb.append(getDeclaringClass().getTypeName()).append('.'); 471 sb.append(getName()); 472 } 473 474 /** 475 * Invokes the underlying method represented by this {@code Method} 476 * object, on the specified object with the specified parameters. 477 * Individual parameters are automatically unwrapped to match 478 * primitive formal parameters, and both primitive and reference 479 * parameters are subject to method invocation conversions as 480 * necessary. 481 * 482 * <p>If the underlying method is static, then the specified {@code obj} 483 * argument is ignored. It may be null. 484 * 485 * <p>If the number of formal parameters required by the underlying method is 486 * 0, the supplied {@code args} array may be of length 0 or null. 487 * 488 * <p>If the underlying method is an instance method, it is invoked 489 * using dynamic method lookup as documented in The Java Language 490 * Specification, Second Edition, section 15.12.4.4; in particular, 491 * overriding based on the runtime type of the target object will occur. 492 * 493 * <p>If the underlying method is static, the class that declared 494 * the method is initialized if it has not already been initialized. 495 * 496 * <p>If the method completes normally, the value it returns is 497 * returned to the caller of invoke; if the value has a primitive 498 * type, it is first appropriately wrapped in an object. However, 499 * if the value has the type of an array of a primitive type, the 500 * elements of the array are <i>not</i> wrapped in objects; in 501 * other words, an array of primitive type is returned. If the 502 * underlying method return type is void, the invocation returns 503 * null. 504 * 505 * @param obj the object the underlying method is invoked from 506 * @param args the arguments used for the method call 507 * @return the result of dispatching the method represented by 508 * this object on {@code obj} with parameters 509 * {@code args} 510 * 511 * @exception IllegalAccessException if this {@code Method} object 512 * is enforcing Java language access control and the underlying 513 * method is inaccessible. 514 * @exception IllegalArgumentException if the method is an 515 * instance method and the specified object argument 516 * is not an instance of the class or interface 517 * declaring the underlying method (or of a subclass 518 * or implementor thereof); if the number of actual 519 * and formal parameters differ; if an unwrapping 520 * conversion for primitive arguments fails; or if, 521 * after possible unwrapping, a parameter value 522 * cannot be converted to the corresponding formal 523 * parameter type by a method invocation conversion. 524 * @exception InvocationTargetException if the underlying method 525 * throws an exception. 526 * @exception NullPointerException if the specified object is null 527 * and the method is an instance method. 528 * @exception ExceptionInInitializerError if the initialization 529 * provoked by this method fails. 530 */ 531 @CallerSensitive 532 @ForceInline // to ensure Reflection.getCallerClass optimization 533 @HotSpotIntrinsicCandidate 534 public Object invoke(Object obj, Object... args) 535 throws IllegalAccessException, IllegalArgumentException, 536 InvocationTargetException 537 { 538 if (!override) { 539 Class<?> caller = Reflection.getCallerClass(); 540 checkAccess(caller, clazz, 541 Modifier.isStatic(modifiers) ? null : obj.getClass(), 542 modifiers); 543 } 544 MethodAccessor ma = methodAccessor; // read volatile 545 if (ma == null) { 546 ma = acquireMethodAccessor(); 547 } 548 return ma.invoke(obj, args); 549 } 550 551 /** 552 * Returns {@code true} if this method is a bridge 553 * method; returns {@code false} otherwise. 554 * 555 * @return true if and only if this method is a bridge 556 * method as defined by the Java Language Specification. 557 * @since 1.5 558 */ 559 public boolean isBridge() { 560 return (getModifiers() & Modifier.BRIDGE) != 0; 561 } 562 563 /** 564 * {@inheritDoc} 565 * @since 1.5 566 */ 567 @Override 568 public boolean isVarArgs() { 569 return super.isVarArgs(); 570 } 571 572 /** 573 * {@inheritDoc} 574 * @jls 13.1 The Form of a Binary 575 * @since 1.5 576 */ 577 @Override 578 public boolean isSynthetic() { 579 return super.isSynthetic(); 580 } 581 582 /** 583 * Returns {@code true} if this method is a default 584 * method; returns {@code false} otherwise. 585 * 586 * A default method is a public non-abstract instance method, that 587 * is, a non-static method with a body, declared in an interface 588 * type. 589 * 590 * @return true if and only if this method is a default 591 * method as defined by the Java Language Specification. 592 * @since 1.8 593 */ 594 public boolean isDefault() { 595 // Default methods are public non-abstract instance methods 596 // declared in an interface. 597 return ((getModifiers() & (Modifier.ABSTRACT | Modifier.PUBLIC | Modifier.STATIC)) == 598 Modifier.PUBLIC) && getDeclaringClass().isInterface(); 599 } 600 601 // NOTE that there is no synchronization used here. It is correct 602 // (though not efficient) to generate more than one MethodAccessor 603 // for a given Method. However, avoiding synchronization will 604 // probably make the implementation more scalable. 605 private MethodAccessor acquireMethodAccessor() { 606 // First check to see if one has been created yet, and take it 607 // if so 608 MethodAccessor tmp = null; 609 if (root != null) tmp = root.getMethodAccessor(); 610 if (tmp != null) { 611 methodAccessor = tmp; 612 } else { 613 // Otherwise fabricate one and propagate it up to the root 614 tmp = reflectionFactory.newMethodAccessor(this); 615 setMethodAccessor(tmp); 616 } 617 618 return tmp; 619 } 620 621 // Returns MethodAccessor for this Method object, not looking up 622 // the chain to the root 623 MethodAccessor getMethodAccessor() { 624 return methodAccessor; 625 } 626 627 // Sets the MethodAccessor for this Method object and 628 // (recursively) its root 629 void setMethodAccessor(MethodAccessor accessor) { 630 methodAccessor = accessor; 631 // Propagate up 632 if (root != null) { 633 root.setMethodAccessor(accessor); 634 } 635 } 636 637 /** 638 * Returns the default value for the annotation member represented by 639 * this {@code Method} instance. If the member is of a primitive type, 640 * an instance of the corresponding wrapper type is returned. Returns 641 * null if no default is associated with the member, or if the method 642 * instance does not represent a declared member of an annotation type. 643 * 644 * @return the default value for the annotation member represented 645 * by this {@code Method} instance. 646 * @throws TypeNotPresentException if the annotation is of type 647 * {@link Class} and no definition can be found for the 648 * default class value. 649 * @since 1.5 650 */ 651 public Object getDefaultValue() { 652 if (annotationDefault == null) 653 return null; 654 Class<?> memberType = AnnotationType.invocationHandlerReturnType( 655 getReturnType()); 656 Object result = AnnotationParser.parseMemberValue( 657 memberType, ByteBuffer.wrap(annotationDefault), 658 SharedSecrets.getJavaLangAccess(). 659 getConstantPool(getDeclaringClass()), 660 getDeclaringClass()); 661 if (result instanceof ExceptionProxy) { 662 if (result instanceof TypeNotPresentExceptionProxy) { 663 TypeNotPresentExceptionProxy proxy = (TypeNotPresentExceptionProxy)result; 664 throw new TypeNotPresentException(proxy.typeName(), proxy.getCause()); 665 } 666 throw new AnnotationFormatError("Invalid default: " + this); 667 } 668 return result; 669 } 670 671 /** 672 * {@inheritDoc} 673 * @throws NullPointerException {@inheritDoc} 674 * @since 1.5 675 */ 676 public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { 677 return super.getAnnotation(annotationClass); 678 } 679 680 /** 681 * {@inheritDoc} 682 * @since 1.5 683 */ 684 public Annotation[] getDeclaredAnnotations() { 685 return super.getDeclaredAnnotations(); 686 } 687 688 /** 689 * {@inheritDoc} 690 * @since 1.5 691 */ 692 @Override 693 public Annotation[][] getParameterAnnotations() { 694 return sharedGetParameterAnnotations(parameterTypes, parameterAnnotations); 695 } 696 697 /** 698 * {@inheritDoc} 699 * @since 1.8 700 */ 701 @Override 702 public AnnotatedType getAnnotatedReturnType() { 703 return getAnnotatedReturnType0(getGenericReturnType()); 704 } 705 706 @Override 707 void handleParameterNumberMismatch(int resultLength, int numParameters) { 708 throw new AnnotationFormatError("Parameter annotations don't match number of parameters"); 709 } 710 }