1/* 2 * Copyright (C) 2014 The Android Open Source Project 3 * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved. 4 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 5 * 6 * This code is free software; you can redistribute it and/or modify it 7 * under the terms of the GNU General Public License version 2 only, as 8 * published by the Free Software Foundation. Oracle designates this 9 * particular file as subject to the "Classpath" exception as provided 10 * by Oracle in the LICENSE file that accompanied this code. 11 * 12 * This code is distributed in the hope that it will be useful, but WITHOUT 13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 14 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 15 * version 2 for more details (a copy is included in the LICENSE file that 16 * accompanied this code). 17 * 18 * You should have received a copy of the GNU General Public License version 19 * 2 along with this work; if not, write to the Free Software Foundation, 20 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 21 * 22 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 23 * or visit www.oracle.com if you need additional information or have any 24 * questions. 25 */ 26 27package java.lang.reflect; 28 29import sun.reflect.CallerSensitive; 30import java.lang.annotation.Annotation; 31import java.lang.annotation.AnnotationFormatError; 32import com.android.dex.Dex; 33import java.util.Comparator; 34import java.util.List; 35import libcore.reflect.Types; 36 37/** 38 * A {@code Method} provides information about, and access to, a single method 39 * on a class or interface. The reflected method may be a class method 40 * or an instance method (including an abstract method). 41 * 42 * <p>A {@code Method} permits widening conversions to occur when matching the 43 * actual parameters to invoke with the underlying method's formal 44 * parameters, but it throws an {@code IllegalArgumentException} if a 45 * narrowing conversion would occur. 46 * 47 * @see Member 48 * @see java.lang.Class 49 * @see java.lang.Class#getMethods() 50 * @see java.lang.Class#getMethod(String, Class[]) 51 * @see java.lang.Class#getDeclaredMethods() 52 * @see java.lang.Class#getDeclaredMethod(String, Class[]) 53 * 54 * @author Kenneth Russell 55 * @author Nakul Saraiya 56 */ 57public final 58 class Method extends AbstractMethod implements GenericDeclaration, 59 Member { 60 /** 61 * Orders methods by their name, parameters and return type. 62 * 63 * @hide 64 */ 65 public static final Comparator<Method> ORDER_BY_SIGNATURE = new Comparator<Method>() { 66 @Override public int compare(Method a, Method b) { 67 if (a == b) { 68 return 0; 69 } 70 int comparison = a.getName().compareTo(b.getName()); 71 if (comparison == 0) { 72 comparison = a.compareParameters(b.getParameterTypes()); 73 if (comparison == 0) { 74 // This is necessary for methods that have covariant return types. 75 Class<?> aReturnType = a.getReturnType(); 76 Class<?> bReturnType = b.getReturnType(); 77 if (aReturnType == bReturnType) { 78 comparison = 0; 79 } else { 80 comparison = aReturnType.getName().compareTo(bReturnType.getName()); 81 } 82 } 83 } 84 return comparison; 85 } 86 }; 87 88 private Method() { 89 } 90 91 /** 92 * Returns the {@code Class} object representing the class or interface 93 * that declares the method represented by this {@code Method} object. 94 */ 95 public Class<?> getDeclaringClass() { 96 return super.getDeclaringClass(); 97 } 98 99 /** 100 * Returns the name of the method represented by this {@code Method} 101 * object, as a {@code String}. 102 */ 103 public String getName() { 104 Dex dex = declaringClassOfOverriddenMethod.getDex(); 105 int nameIndex = dex.nameIndexFromMethodIndex(dexMethodIndex); 106 return declaringClassOfOverriddenMethod.getDexCacheString(dex, nameIndex); 107 } 108 109 /** 110 * Returns the Java language modifiers for the method represented 111 * by this {@code Method} object, as an integer. The {@code Modifier} class should 112 * be used to decode the modifiers. 113 * 114 * @see Modifier 115 */ 116 public int getModifiers() { 117 return super.getModifiers(); 118 } 119 120 /** 121 * Returns an array of {@code TypeVariable} objects that represent the 122 * type variables declared by the generic declaration represented by this 123 * {@code GenericDeclaration} object, in declaration order. Returns an 124 * array of length 0 if the underlying generic declaration declares no type 125 * variables. 126 * 127 * @return an array of {@code TypeVariable} objects that represent 128 * the type variables declared by this generic declaration 129 * @throws GenericSignatureFormatError if the generic 130 * signature of this generic declaration does not conform to 131 * the format specified in 132 * <cite>The Java™ Virtual Machine Specification</cite> 133 * @since 1.5 134 */ 135 public TypeVariable<Method>[] getTypeParameters() { 136 GenericInfo info = getMethodOrConstructorGenericInfo(); 137 return (TypeVariable<Method>[]) info.formalTypeParameters.clone(); 138 } 139 140 /** 141 * Returns a {@code Class} object that represents the formal return type 142 * of the method represented by this {@code Method} object. 143 * 144 * @return the return type for the method this object represents 145 */ 146 public Class<?> getReturnType() { 147 Dex dex = declaringClassOfOverriddenMethod.getDex(); 148 int returnTypeIndex = dex.returnTypeIndexFromMethodIndex(dexMethodIndex); 149 // Note, in the case of a Proxy the dex cache types are equal. 150 return declaringClassOfOverriddenMethod.getDexCacheType(dex, returnTypeIndex); 151 } 152 153 /** 154 * Returns a {@code Type} object that represents the formal return 155 * type of the method represented by this {@code Method} object. 156 * 157 * <p>If the return type is a parameterized type, 158 * the {@code Type} object returned must accurately reflect 159 * the actual type parameters used in the source code. 160 * 161 * <p>If the return type is a type variable or a parameterized type, it 162 * is created. Otherwise, it is resolved. 163 * 164 * @return a {@code Type} object that represents the formal return 165 * type of the underlying method 166 * @throws GenericSignatureFormatError 167 * if the generic method signature does not conform to the format 168 * specified in 169 * <cite>The Java™ Virtual Machine Specification</cite> 170 * @throws TypeNotPresentException if the underlying method's 171 * return type refers to a non-existent type declaration 172 * @throws MalformedParameterizedTypeException if the 173 * underlying method's return typed refers to a parameterized 174 * type that cannot be instantiated for any reason 175 * @since 1.5 176 */ 177 public Type getGenericReturnType() { 178 return Types.getType(getMethodOrConstructorGenericInfo().genericReturnType); 179 } 180 181 182 /** 183 * Returns an array of {@code Class} objects that represent the formal 184 * parameter types, in declaration order, of the method 185 * represented by this {@code Method} object. Returns an array of length 186 * 0 if the underlying method takes no parameters. 187 * 188 * @return the parameter types for the method this object 189 * represents 190 */ 191 @Override 192 public Class<?>[] getParameterTypes() { 193 return super.getParameterTypes(); 194 } 195 196 /** 197 * Returns an array of {@code Type} objects that represent the formal 198 * parameter types, in declaration order, of the method represented by 199 * this {@code Method} object. Returns an array of length 0 if the 200 * underlying method takes no parameters. 201 * 202 * <p>If a formal parameter type is a parameterized type, 203 * the {@code Type} object returned for it must accurately reflect 204 * the actual type parameters used in the source code. 205 * 206 * <p>If a formal parameter type is a type variable or a parameterized 207 * type, it is created. Otherwise, it is resolved. 208 * 209 * @return an array of Types that represent the formal 210 * parameter types of the underlying method, in declaration order 211 * @throws GenericSignatureFormatError 212 * if the generic method signature does not conform to the format 213 * specified in 214 * <cite>The Java™ Virtual Machine Specification</cite> 215 * @throws TypeNotPresentException if any of the parameter 216 * types of the underlying method refers to a non-existent type 217 * declaration 218 * @throws MalformedParameterizedTypeException if any of 219 * the underlying method's parameter types refer to a parameterized 220 * type that cannot be instantiated for any reason 221 * @since 1.5 222 */ 223 public Type[] getGenericParameterTypes() { 224 return Types.getTypeArray(getMethodOrConstructorGenericInfo().genericParameterTypes, false); 225 } 226 227 /** 228 * Returns an array of {@code Class} objects that represent 229 * the types of the exceptions declared to be thrown 230 * by the underlying method 231 * represented by this {@code Method} object. Returns an array of length 232 * 0 if the method declares no exceptions in its {@code throws} clause. 233 * 234 * @return the exception types declared as being thrown by the 235 * method this object represents 236 */ 237 public native Class<?>[] getExceptionTypes(); 238 239 /** 240 * Returns an array of {@code Type} objects that represent the 241 * exceptions declared to be thrown by this {@code Method} object. 242 * Returns an array of length 0 if the underlying method declares 243 * no exceptions in its {@code throws} clause. 244 * 245 * <p>If an exception type is a type variable or a parameterized 246 * type, it is created. Otherwise, it is resolved. 247 * 248 * @return an array of Types that represent the exception types 249 * thrown by the underlying method 250 * @throws GenericSignatureFormatError 251 * if the generic method signature does not conform to the format 252 * specified in 253 * <cite>The Java™ Virtual Machine Specification</cite> 254 * @throws TypeNotPresentException if the underlying method's 255 * {@code throws} clause refers to a non-existent type declaration 256 * @throws MalformedParameterizedTypeException if 257 * the underlying method's {@code throws} clause refers to a 258 * parameterized type that cannot be instantiated for any reason 259 * @since 1.5 260 */ 261 public Type[] getGenericExceptionTypes() { 262 return Types.getTypeArray(getMethodOrConstructorGenericInfo().genericExceptionTypes, false); 263 } 264 265 /** 266 * Compares this {@code Method} against the specified object. Returns 267 * true if the objects are the same. Two {@code Methods} are the same if 268 * they were declared by the same class and have the same name 269 * and formal parameter types and return type. 270 */ 271 public boolean equals(Object obj) { 272 if (obj != null && obj instanceof Method) { 273 Method other = (Method)obj; 274 if ((getDeclaringClass() == other.getDeclaringClass()) 275 && (getName() == other.getName())) { 276 if (!getReturnType().equals(other.getReturnType())) 277 return false; 278 /* Avoid unnecessary cloning */ 279 Class<?>[] params1 = getParameterTypes(); 280 Class<?>[] params2 = other.getParameterTypes(); 281 if (params1.length == params2.length) { 282 for (int i = 0; i < params1.length; i++) { 283 if (params1[i] != params2[i]) 284 return false; 285 } 286 return true; 287 } 288 } 289 } 290 return false; 291 } 292 293 /** 294 * Returns a hashcode for this {@code Method}. The hashcode is computed 295 * as the exclusive-or of the hashcodes for the underlying 296 * method's declaring class name and the method's name. 297 */ 298 public int hashCode() { 299 return getDeclaringClass().getName().hashCode() ^ getName().hashCode(); 300 } 301 302 /** 303 * Returns a string describing this {@code Method}. The string is 304 * formatted as the method access modifiers, if any, followed by 305 * the method return type, followed by a space, followed by the 306 * class declaring the method, followed by a period, followed by 307 * the method name, followed by a parenthesized, comma-separated 308 * list of the method's formal parameter types. If the method 309 * throws checked exceptions, the parameter list is followed by a 310 * space, followed by the word throws followed by a 311 * comma-separated list of the thrown exception types. 312 * For example: 313 * <pre> 314 * public boolean java.lang.Object.equals(java.lang.Object) 315 * </pre> 316 * 317 * <p>The access modifiers are placed in canonical order as 318 * specified by "The Java Language Specification". This is 319 * {@code public}, {@code protected} or {@code private} first, 320 * and then other modifiers in the following order: 321 * {@code abstract}, {@code static}, {@code final}, 322 * {@code synchronized}, {@code native}, {@code strictfp}. 323 */ 324 public String toString() { 325 try { 326 StringBuilder sb = new StringBuilder(); 327 int mod = getModifiers() & Modifier.methodModifiers(); 328 if (mod != 0) { 329 sb.append(Modifier.toString(mod)).append(' '); 330 } 331 sb.append(Field.getTypeName(getReturnType())).append(' '); 332 sb.append(Field.getTypeName(getDeclaringClass())).append('.'); 333 sb.append(getName()).append('('); 334 Class<?>[] params = getParameterTypes(); 335 for (int j = 0; j < params.length; j++) { 336 sb.append(Field.getTypeName(params[j])); 337 if (j < (params.length - 1)) 338 sb.append(','); 339 } 340 sb.append(')'); 341 Class<?>[] exceptions = getExceptionTypes(); 342 if (exceptions.length > 0) { 343 sb.append(" throws "); 344 for (int k = 0; k < exceptions.length; k++) { 345 sb.append(exceptions[k].getName()); 346 if (k < (exceptions.length - 1)) 347 sb.append(','); 348 } 349 } 350 return sb.toString(); 351 } catch (Exception e) { 352 return "<" + e + ">"; 353 } 354 } 355 356 /** 357 * Returns a string describing this {@code Method}, including 358 * type parameters. The string is formatted as the method access 359 * modifiers, if any, followed by an angle-bracketed 360 * comma-separated list of the method's type parameters, if any, 361 * followed by the method's generic return type, followed by a 362 * space, followed by the class declaring the method, followed by 363 * a period, followed by the method name, followed by a 364 * parenthesized, comma-separated list of the method's generic 365 * formal parameter types. 366 * 367 * If this method was declared to take a variable number of 368 * arguments, instead of denoting the last parameter as 369 * "<tt><i>Type</i>[]</tt>", it is denoted as 370 * "<tt><i>Type</i>...</tt>". 371 * 372 * A space is used to separate access modifiers from one another 373 * and from the type parameters or return type. If there are no 374 * type parameters, the type parameter list is elided; if the type 375 * parameter list is present, a space separates the list from the 376 * class name. If the method is declared to throw exceptions, the 377 * parameter list is followed by a space, followed by the word 378 * throws followed by a comma-separated list of the generic thrown 379 * exception types. If there are no type parameters, the type 380 * parameter list is elided. 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 static}, {@code final}, 387 * {@code synchronized}, {@code native}, {@code strictfp}. 388 * 389 * @return a string describing this {@code Method}, 390 * include type parameters 391 * 392 * @since 1.5 393 */ 394 public String toGenericString() { 395 try { 396 StringBuilder sb = new StringBuilder(); 397 int mod = getModifiers() & Modifier.methodModifiers(); 398 if (mod != 0) { 399 sb.append(Modifier.toString(mod)).append(' '); 400 } 401 TypeVariable<?>[] typeparms = getTypeParameters(); 402 if (typeparms.length > 0) { 403 boolean first = true; 404 sb.append('<'); 405 for(TypeVariable<?> typeparm: typeparms) { 406 if (!first) 407 sb.append(','); 408 // Class objects can't occur here; no need to test 409 // and call Class.getName(). 410 sb.append(typeparm.toString()); 411 first = false; 412 } 413 sb.append("> "); 414 } 415 416 Type genRetType = getGenericReturnType(); 417 sb.append( ((genRetType instanceof Class<?>)? 418 Field.getTypeName((Class<?>)genRetType):genRetType.toString())) 419 .append(' '); 420 421 sb.append(Field.getTypeName(getDeclaringClass())).append('.'); 422 sb.append(getName()).append('('); 423 Type[] params = getGenericParameterTypes(); 424 for (int j = 0; j < params.length; j++) { 425 String param = (params[j] instanceof Class)? 426 Field.getTypeName((Class)params[j]): 427 (params[j].toString()); 428 if (isVarArgs() && (j == params.length - 1)) // replace T[] with T... 429 param = param.replaceFirst("\\[\\]$", "..."); 430 sb.append(param); 431 if (j < (params.length - 1)) 432 sb.append(','); 433 } 434 sb.append(')'); 435 Type[] exceptions = getGenericExceptionTypes(); 436 if (exceptions.length > 0) { 437 sb.append(" throws "); 438 for (int k = 0; k < exceptions.length; k++) { 439 sb.append((exceptions[k] instanceof Class)? 440 ((Class)exceptions[k]).getName(): 441 exceptions[k].toString()); 442 if (k < (exceptions.length - 1)) 443 sb.append(','); 444 } 445 } 446 return sb.toString(); 447 } catch (Exception e) { 448 return "<" + e + ">"; 449 } 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 receiver 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 public native Object invoke(Object receiver, Object... args) 510 throws IllegalAccessException, IllegalArgumentException, InvocationTargetException; 511 512 /** 513 * Returns {@code true} if this method is a bridge 514 * method; returns {@code false} otherwise. 515 * 516 * @return true if and only if this method is a bridge 517 * method as defined by the Java Language Specification. 518 * @since 1.5 519 */ 520 public boolean isBridge() { 521 return (getModifiers() & Modifier.BRIDGE) != 0; 522 } 523 524 /** 525 * Returns {@code true} if this method was declared to take 526 * a variable number of arguments; returns {@code false} 527 * otherwise. 528 * 529 * @return {@code true} if an only if this method was declared to 530 * take a variable number of arguments. 531 * @since 1.5 532 */ 533 public boolean isVarArgs() { 534 return (getModifiers() & Modifier.VARARGS) != 0; 535 } 536 537 /** 538 * Returns {@code true} if this method is a synthetic 539 * method; returns {@code false} otherwise. 540 * 541 * @return true if and only if this method is a synthetic 542 * method as defined by the Java Language Specification. 543 * @since 1.5 544 */ 545 public boolean isSynthetic() { 546 return Modifier.isSynthetic(getModifiers()); 547 } 548 549 /** 550 * @throws NullPointerException {@inheritDoc} 551 * @since 1.5 552 */ 553 @Override public <A extends Annotation> A getAnnotation(Class<A> annotationType) { 554 if (annotationType == null) { 555 throw new NullPointerException("annotationType == null"); 556 } 557 return getAnnotationNative(annotationType); 558 } 559 private native <A extends Annotation> A getAnnotationNative(Class<A> annotationType); 560 561 /** 562 * Returns the default value for the annotation member represented by 563 * this {@code Method} instance. If the member is of a primitive type, 564 * an instance of the corresponding wrapper type is returned. Returns 565 * null if no default is associated with the member, or if the method 566 * instance does not represent a declared member of an annotation type. 567 * 568 * @return the default value for the annotation member represented 569 * by this {@code Method} instance. 570 * @throws TypeNotPresentException if the annotation is of type 571 * {@link Class} and no definition can be found for the 572 * default class value. 573 * @since 1.5 574 */ 575 public native Object getDefaultValue(); 576 577 /** 578 * Returns an array of arrays that represent the annotations on the formal 579 * parameters, in declaration order, of the method represented by 580 * this {@code Method} object. (Returns an array of length zero if the 581 * underlying method is parameterless. If the method has one or more 582 * parameters, a nested array of length zero is returned for each parameter 583 * with no annotations.) The annotation objects contained in the returned 584 * arrays are serializable. The caller of this method is free to modify 585 * the returned arrays; it will have no effect on the arrays returned to 586 * other callers. 587 * 588 * @return an array of arrays that represent the annotations on the formal 589 * parameters, in declaration order, of the method represented by this 590 * Method object 591 * @since 1.5 592 */ 593 public Annotation[][] getParameterAnnotations() { 594 Annotation[][] parameterAnnotations = getParameterAnnotationsNative(); 595 if (parameterAnnotations == null) { 596 parameterAnnotations = new Annotation[getParameterTypes().length][0]; 597 } 598 return parameterAnnotations; 599 } 600 private native Annotation[][] getParameterAnnotationsNative(); 601 602 /** 603 * Returns the constructor's signature in non-printable form. This is called 604 * (only) from IO native code and needed for deriving the serialVersionUID 605 * of the class 606 * 607 * @return The constructor's signature. 608 */ 609 @SuppressWarnings("unused") 610 String getSignature() { 611 StringBuilder result = new StringBuilder(); 612 613 result.append('('); 614 Class<?>[] parameterTypes = getParameterTypes(); 615 for (Class<?> parameterType : parameterTypes) { 616 result.append(Types.getSignature(parameterType)); 617 } 618 result.append(')'); 619 result.append(Types.getSignature(getReturnType())); 620 621 return result.toString(); 622 } 623 /** 624 * Returns true if this and {@code method} have the same name and the same 625 * parameters in the same order. Such methods can share implementation if 626 * one method's return types is assignable to the other. 627 * 628 * @hide needed by Proxy 629 */ 630 boolean equalNameAndParameters(Method m) { 631 return getName().equals(m.getName()) && equalMethodParameters(m.getParameterTypes()); 632 } 633 634 /** 635 * Returns {@code true} if this method is a default method; returns {@code false} otherwise. 636 */ 637 public boolean isDefault() { 638 return super.isDefault(); 639 } 640} 641