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