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