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