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