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