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