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