1 /* 2 * Copyright 1996-2006 Sun Microsystems, Inc. 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. Sun designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, 22 * CA 95054 USA or visit www.sun.com if you need additional information or 23 * have any questions. 24 */ 25 26 package java.lang.reflect; 27 28 import sun.reflect.MethodAccessor; 29 import sun.reflect.Reflection; 30 import sun.reflect.generics.repository.MethodRepository; 31 import sun.reflect.generics.factory.CoreReflectionFactory; 32 import sun.reflect.generics.factory.GenericsFactory; 33 import sun.reflect.generics.scope.MethodScope; 34 import sun.reflect.annotation.AnnotationType; 35 import sun.reflect.annotation.AnnotationParser; 36 import java.lang.annotation.Annotation; 37 import java.lang.annotation.AnnotationFormatError; 38 import java.nio.ByteBuffer; 39 import java.util.Map; 40 41 /** 42 * A {@code Method} provides information about, and access to, a single method 43 * on a class or interface. The reflected method may be a class method 44 * or an instance method (including an abstract method). 45 * 46 * <p>A {@code Method} permits widening conversions to occur when matching the 47 * actual parameters to invoke with the underlying method's formal 48 * parameters, but it throws an {@code IllegalArgumentException} if a 49 * narrowing conversion would occur. 50 * 51 * @see Member 52 * @see java.lang.Class 53 * @see java.lang.Class#getMethods() 54 * @see java.lang.Class#getMethod(String, Class[]) 55 * @see java.lang.Class#getDeclaredMethods() 56 * @see java.lang.Class#getDeclaredMethod(String, Class[]) 57 * 58 * @author Kenneth Russell 59 * @author Nakul Saraiya 60 */ 61 public final 62 class Method extends AccessibleObject implements GenericDeclaration, 63 Member { 64 private Class clazz; 65 private int slot; 66 // This is guaranteed to be interned by the VM in the 1.4 67 // reflection implementation 68 private String name; 69 private Class returnType; 70 private Class[] parameterTypes; 71 private Class[] exceptionTypes; 72 private int modifiers; 73 // Generics and annotations support 74 private transient String signature; 75 // generic info repository; lazily initialized 76 private transient MethodRepository genericInfo; 77 private byte[] annotations; 78 private byte[] parameterAnnotations; 79 private byte[] annotationDefault; 80 private volatile MethodAccessor methodAccessor; 81 // For sharing of MethodAccessors. This branching structure is 82 // currently only two levels deep (i.e., one root Method and 83 // potentially many Method objects pointing to it.) 84 private Method root; 85 86 // More complicated security check cache needed here than for 87 // Class.newInstance() and Constructor.newInstance() 88 private Class securityCheckCache; 89 private Class securityCheckTargetClassCache; 90 91 // Generics infrastructure 92 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 private MethodRepository getGenericInfo() { 103 // lazily initialize repository if necessary 104 if (genericInfo == null) { 105 // create and cache generic info repository 106 genericInfo = MethodRepository.make(getGenericSignature(), 107 getFactory()); 108 } 109 return genericInfo; //return cached repository 110 } 111 112 /** 113 * Package-private constructor used by ReflectAccess to enable 114 * instantiation of these objects in Java code from the java.lang 115 * package via sun.reflect.LangReflectAccess. 116 */ 117 Method(Class declaringClass, 118 String name, 119 Class[] parameterTypes, 120 Class returnType, 121 Class[] checkedExceptions, 122 int modifiers, 123 int slot, 124 String signature, 125 byte[] annotations, 126 byte[] parameterAnnotations, 127 byte[] annotationDefault) 128 { 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 Method res = new Method(clazz, name, parameterTypes, returnType, 156 exceptionTypes, modifiers, slot, signature, 157 annotations, parameterAnnotations, annotationDefault); 158 res.root = this; 159 // Might as well eagerly propagate this if already present 160 res.methodAccessor = methodAccessor; 161 return res; 162 } 163 164 /** 165 * Returns the {@code Class} object representing the class or interface 166 * that declares the method represented by this {@code Method} object. 167 */ 168 public Class<?> getDeclaringClass() { 169 return clazz; 170 } 171 172 /** 173 * Returns the name of the method represented by this {@code Method} 174 * object, as a {@code String}. 175 */ 176 public String getName() { 177 return name; 178 } 179 180 /** 181 * Returns the Java language modifiers for the method represented 182 * by this {@code Method} object, as an integer. The {@code Modifier} class should 183 * be used to decode the modifiers. 184 * 185 * @see Modifier 186 */ 187 public int getModifiers() { 188 return modifiers; 189 } 190 191 /** 192 * Returns an array of {@code TypeVariable} objects that represent the 193 * type variables declared by the generic declaration represented by this 194 * {@code GenericDeclaration} object, in declaration order. Returns an 195 * array of length 0 if the underlying generic declaration declares no type 196 * variables. 197 * 198 * @return an array of {@code TypeVariable} objects that represent 199 * the type variables declared by this generic declaration 200 * @throws GenericSignatureFormatError if the generic 201 * signature of this generic declaration does not conform to 202 * the format specified in the Java Virtual Machine Specification, 203 * 3rd edition 204 * @since 1.5 205 */ 206 public TypeVariable<Method>[] getTypeParameters() { 207 if (getGenericSignature() != null) 208 return (TypeVariable<Method>[])getGenericInfo().getTypeParameters(); 209 else 210 return (TypeVariable<Method>[])new TypeVariable[0]; 211 } 212 213 /** 214 * Returns a {@code Class} object that represents the formal return type 215 * of the method represented by this {@code Method} object. 216 * 217 * @return the return type for the method this object represents 218 */ 219 public Class<?> getReturnType() { 220 return returnType; 221 } 222 223 /** 224 * Returns a {@code Type} object that represents the formal return 225 * type of the method represented by this {@code Method} object. 226 * 227 * <p>If the return type is a parameterized type, 228 * the {@code Type} object returned must accurately reflect 229 * the actual type parameters used in the source code. 230 * 231 * <p>If the return type is a type variable or a parameterized type, it 232 * is created. Otherwise, it is resolved. 233 * 234 * @return a {@code Type} object that represents the formal return 235 * type of the underlying method 236 * @throws GenericSignatureFormatError 237 * if the generic method signature does not conform to the format 238 * specified in the Java Virtual Machine Specification, 3rd edition 239 * @throws TypeNotPresentException if the underlying method's 240 * return type refers to a non-existent type declaration 241 * @throws MalformedParameterizedTypeException if the 242 * underlying method's return typed refers to a parameterized 243 * type that cannot be instantiated for any reason 244 * @since 1.5 245 */ 246 public Type getGenericReturnType() { 247 if (getGenericSignature() != null) { 248 return getGenericInfo().getReturnType(); 249 } else { return getReturnType();} 250 } 251 252 253 /** 254 * Returns an array of {@code Class} objects that represent the formal 255 * parameter types, in declaration order, of the method 256 * represented by this {@code Method} object. Returns an array of length 257 * 0 if the underlying method takes no parameters. 258 * 259 * @return the parameter types for the method this object 260 * represents 261 */ 262 public Class<?>[] getParameterTypes() { 263 return (Class<?>[]) parameterTypes.clone(); 264 } 265 266 /** 267 * Returns an array of {@code Type} objects that represent the formal 268 * parameter types, in declaration order, of the method represented by 269 * this {@code Method} object. Returns an array of length 0 if the 270 * underlying method takes no parameters. 271 * 272 * <p>If a formal parameter type is a parameterized type, 273 * the {@code Type} object returned for it must accurately reflect 274 * the actual type parameters used in the source code. 275 * 276 * <p>If a formal parameter type is a type variable or a parameterized 277 * type, it is created. Otherwise, it is resolved. 278 * 279 * @return an array of Types that represent the formal 280 * parameter types of the underlying method, in declaration order 281 * @throws GenericSignatureFormatError 282 * if the generic method signature does not conform to the format 283 * specified in the Java Virtual Machine Specification, 3rd edition 284 * @throws TypeNotPresentException if any of the parameter 285 * types of the underlying method refers to a non-existent type 286 * declaration 287 * @throws MalformedParameterizedTypeException if any of 288 * the underlying method's parameter types refer to a parameterized 289 * type that cannot be instantiated for any reason 290 * @since 1.5 291 */ 292 public Type[] getGenericParameterTypes() { 293 if (getGenericSignature() != null) 294 return getGenericInfo().getParameterTypes(); 295 else 296 return getParameterTypes(); 297 } 298 299 300 /** 301 * Returns an array of {@code Class} objects that represent 302 * the types of the exceptions declared to be thrown 303 * by the underlying method 304 * represented by this {@code Method} object. Returns an array of length 305 * 0 if the method declares no exceptions in its {@code throws} clause. 306 * 307 * @return the exception types declared as being thrown by the 308 * method this object represents 309 */ 310 public Class<?>[] getExceptionTypes() { 311 return (Class<?>[]) exceptionTypes.clone(); 312 } 313 314 /** 315 * Returns an array of {@code Type} objects that represent the 316 * exceptions declared to be thrown by this {@code Method} object. 317 * Returns an array of length 0 if the underlying method declares 318 * no exceptions in its {@code throws} clause. 319 * 320 * <p>If an exception type is a parameterized type, the {@code Type} 321 * object returned for it must accurately reflect the actual type 322 * parameters used in the source code. 323 * 324 * <p>If an exception type is a type variable or a parameterized 325 * type, it is created. Otherwise, it is resolved. 326 * 327 * @return an array of Types that represent the exception types 328 * thrown by the underlying method 329 * @throws GenericSignatureFormatError 330 * if the generic method signature does not conform to the format 331 * specified in the Java Virtual Machine Specification, 3rd edition 332 * @throws TypeNotPresentException if the underlying method's 333 * {@code throws} clause refers to a non-existent type declaration 334 * @throws MalformedParameterizedTypeException if 335 * the underlying method's {@code throws} clause refers to a 336 * parameterized type that cannot be instantiated for any reason 337 * @since 1.5 338 */ 339 public Type[] getGenericExceptionTypes() { 340 Type[] result; 341 if (getGenericSignature() != null && 342 ((result = getGenericInfo().getExceptionTypes()).length > 0)) 343 return result; 344 else 345 return getExceptionTypes(); 346 } 347 348 /** 349 * Compares this {@code Method} against the specified object. Returns 350 * true if the objects are the same. Two {@code Methods} are the same if 351 * they were declared by the same class and have the same name 352 * and formal parameter types and return type. 353 */ 354 public boolean equals(Object obj) { 355 if (obj != null && obj instanceof Method) { 356 Method other = (Method)obj; 357 if ((getDeclaringClass() == other.getDeclaringClass()) 358 && (getName() == other.getName())) { 359 if (!returnType.equals(other.getReturnType())) 360 return false; 361 /* Avoid unnecessary cloning */ 362 Class[] params1 = parameterTypes; 363 Class[] params2 = other.parameterTypes; 364 if (params1.length == params2.length) { 365 for (int i = 0; i < params1.length; i++) { 366 if (params1[i] != params2[i]) 367 return false; 368 } 369 return true; 370 } 371 } 372 } 373 return false; 374 } 375 376 /** 377 * Returns a hashcode for this {@code Method}. The hashcode is computed 378 * as the exclusive-or of the hashcodes for the underlying 379 * method's declaring class name and the method's name. 380 */ 381 public int hashCode() { 382 return getDeclaringClass().getName().hashCode() ^ getName().hashCode(); 383 } 384 385 /** 386 * Returns a string describing this {@code Method}. The string is 387 * formatted as the method access modifiers, if any, followed by 388 * the method return type, followed by a space, followed by the 389 * class declaring the method, followed by a period, followed by 390 * the method name, followed by a parenthesized, comma-separated 391 * list of the method's formal parameter types. If the method 392 * throws checked exceptions, the parameter list is followed by a 393 * space, followed by the word throws followed by a 394 * comma-separated list of the thrown exception types. 395 * For example: 396 * <pre> 397 * public boolean java.lang.Object.equals(java.lang.Object) 398 * </pre> 399 * 400 * <p>The access modifiers are placed in canonical order as 401 * specified by "The Java Language Specification". This is 402 * {@code public}, {@code protected} or {@code private} first, 403 * and then other modifiers in the following order: 404 * {@code abstract}, {@code static}, {@code final}, 405 * {@code synchronized}, {@code native}, {@code strictfp}. 406 */ 407 public String toString() { 408 try { 409 StringBuffer sb = new StringBuffer(); 410 int mod = getModifiers() & Modifier.methodModifiers(); 411 if (mod != 0) { 412 sb.append(Modifier.toString(mod) + " "); 413 } 414 sb.append(Field.getTypeName(getReturnType()) + " "); 415 sb.append(Field.getTypeName(getDeclaringClass()) + "."); 416 sb.append(getName() + "("); 417 Class[] params = parameterTypes; // avoid clone 418 for (int j = 0; j < params.length; j++) { 419 sb.append(Field.getTypeName(params[j])); 420 if (j < (params.length - 1)) 421 sb.append(","); 422 } 423 sb.append(")"); 424 Class[] exceptions = exceptionTypes; // avoid clone 425 if (exceptions.length > 0) { 426 sb.append(" throws "); 427 for (int k = 0; k < exceptions.length; k++) { 428 sb.append(exceptions[k].getName()); 429 if (k < (exceptions.length - 1)) 430 sb.append(","); 431 } 432 } 433 return sb.toString(); 434 } catch (Exception e) { 435 return "<" + e + ">"; 436 } 437 } 438 439 /** 440 * Returns a string describing this {@code Method}, including 441 * type parameters. The string is formatted as the method access 442 * modifiers, if any, followed by an angle-bracketed 443 * comma-separated list of the method's type parameters, if any, 444 * followed by the method's generic return type, followed by a 445 * space, followed by the class declaring the method, followed by 446 * a period, followed by the method name, followed by a 447 * parenthesized, comma-separated list of the method's generic 448 * formal parameter types. 449 * 450 * If this method was declared to take a variable number of 451 * arguments, instead of denoting the last parameter as 452 * "<tt><i>Type</i>[]</tt>", it is denoted as 453 * "<tt><i>Type</i>...</tt>". 454 * 455 * A space is used to separate access modifiers from one another 456 * and from the type parameters or return type. If there are no 457 * type parameters, the type parameter list is elided; if the type 458 * parameter list is present, a space separates the list from the 459 * class name. If the method is declared to throw exceptions, the 460 * parameter list is followed by a space, followed by the word 461 * throws followed by a comma-separated list of the generic thrown 462 * exception types. If there are no type parameters, the type 463 * parameter list is elided. 464 * 465 * <p>The access modifiers are placed in canonical order as 466 * specified by "The Java Language Specification". This is 467 * {@code public}, {@code protected} or {@code private} first, 468 * and then other modifiers in the following order: 469 * {@code abstract}, {@code static}, {@code final}, 470 * {@code synchronized}, {@code native}, {@code strictfp}. 471 * 472 * @return a string describing this {@code Method}, 473 * include type parameters 474 * 475 * @since 1.5 476 */ 477 public String toGenericString() { 478 try { 479 StringBuilder sb = new StringBuilder(); 480 int mod = getModifiers() & Modifier.methodModifiers(); 481 if (mod != 0) { 482 sb.append(Modifier.toString(mod) + " "); 483 } 484 TypeVariable<?>[] typeparms = getTypeParameters(); 485 if (typeparms.length > 0) { 486 boolean first = true; 487 sb.append("<"); 488 for(TypeVariable<?> typeparm: typeparms) { 489 if (!first) 490 sb.append(","); 491 // Class objects can't occur here; no need to test 492 // and call Class.getName(). 493 sb.append(typeparm.toString()); 494 first = false; 495 } 496 sb.append("> "); 497 } 498 499 Type genRetType = getGenericReturnType(); 500 sb.append( ((genRetType instanceof Class<?>)? 501 Field.getTypeName((Class<?>)genRetType):genRetType.toString()) + " "); 502 503 sb.append(Field.getTypeName(getDeclaringClass()) + "."); 504 sb.append(getName() + "("); 505 Type[] params = getGenericParameterTypes(); 506 for (int j = 0; j < params.length; j++) { 507 String param = (params[j] instanceof Class)? 508 Field.getTypeName((Class)params[j]): 509 (params[j].toString()); 510 if (isVarArgs() && (j == params.length - 1)) // replace T[] with T... 511 param = param.replaceFirst("\\[\\]$", "..."); 512 sb.append(param); 513 if (j < (params.length - 1)) 514 sb.append(","); 515 } 516 sb.append(")"); 517 Type[] exceptions = getGenericExceptionTypes(); 518 if (exceptions.length > 0) { 519 sb.append(" throws "); 520 for (int k = 0; k < exceptions.length; k++) { 521 sb.append((exceptions[k] instanceof Class)? 522 ((Class)exceptions[k]).getName(): 523 exceptions[k].toString()); 524 if (k < (exceptions.length - 1)) 525 sb.append(","); 526 } 527 } 528 return sb.toString(); 529 } catch (Exception e) { 530 return "<" + e + ">"; 531 } 532 } 533 534 /** 535 * Invokes the underlying method represented by this {@code Method} 536 * object, on the specified object with the specified parameters. 537 * Individual parameters are automatically unwrapped to match 538 * primitive formal parameters, and both primitive and reference 539 * parameters are subject to method invocation conversions as 540 * necessary. 541 * 542 * <p>If the underlying method is static, then the specified {@code obj} 543 * argument is ignored. It may be null. 544 * 545 * <p>If the number of formal parameters required by the underlying method is 546 * 0, the supplied {@code args} array may be of length 0 or null. 547 * 548 * <p>If the underlying method is an instance method, it is invoked 549 * using dynamic method lookup as documented in The Java Language 550 * Specification, Second Edition, section 15.12.4.4; in particular, 551 * overriding based on the runtime type of the target object will occur. 552 * 553 * <p>If the underlying method is static, the class that declared 554 * the method is initialized if it has not already been initialized. 555 * 556 * <p>If the method completes normally, the value it returns is 557 * returned to the caller of invoke; if the value has a primitive 558 * type, it is first appropriately wrapped in an object. However, 559 * if the value has the type of an array of a primitive type, the 560 * elements of the array are <i>not</i> wrapped in objects; in 561 * other words, an array of primitive type is returned. If the 562 * underlying method return type is void, the invocation returns 563 * null. 564 * 565 * @param obj the object the underlying method is invoked from 566 * @param args the arguments used for the method call 567 * @return the result of dispatching the method represented by 568 * this object on {@code obj} with parameters 569 * {@code args} 570 * 571 * @exception IllegalAccessException if this {@code Method} object 572 * enforces Java language access control and the underlying 573 * method is inaccessible. 574 * @exception IllegalArgumentException if the method is an 575 * instance method and the specified object argument 576 * is not an instance of the class or interface 577 * declaring the underlying method (or of a subclass 578 * or implementor thereof); if the number of actual 579 * and formal parameters differ; if an unwrapping 580 * conversion for primitive arguments fails; or if, 581 * after possible unwrapping, a parameter value 582 * cannot be converted to the corresponding formal 583 * parameter type by a method invocation conversion. 584 * @exception InvocationTargetException if the underlying method 585 * throws an exception. 586 * @exception NullPointerException if the specified object is null 587 * and the method is an instance method. 588 * @exception ExceptionInInitializerError if the initialization 589 * provoked by this method fails. 590 */ 591 public Object invoke(Object obj, Object... args) 592 throws IllegalAccessException, IllegalArgumentException, 593 InvocationTargetException 594 { 595 if (!override) { 596 if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) { 597 Class caller = Reflection.getCallerClass(1); 598 Class targetClass = ((obj == null || !Modifier.isProtected(modifiers)) 599 ? clazz 600 : obj.getClass()); 601 602 boolean cached; 603 synchronized (this) { 604 cached = (securityCheckCache == caller) 605 && (securityCheckTargetClassCache == targetClass); 606 } 607 if (!cached) { 608 Reflection.ensureMemberAccess(caller, clazz, obj, modifiers); 609 synchronized (this) { 610 securityCheckCache = caller; 611 securityCheckTargetClassCache = targetClass; 612 } 613 } 614 } 615 } 616 if (methodAccessor == null) acquireMethodAccessor(); 617 return methodAccessor.invoke(obj, args); 618 } 619 620 /** 621 * Returns {@code true} if this method is a bridge 622 * method; returns {@code false} otherwise. 623 * 624 * @return true if and only if this method is a bridge 625 * method as defined by the Java Language Specification. 626 * @since 1.5 627 */ 628 public boolean isBridge() { 629 return (getModifiers() & Modifier.BRIDGE) != 0; 630 } 631 632 /** 633 * Returns {@code true} if this method was declared to take 634 * a variable number of arguments; returns {@code false} 635 * otherwise. 636 * 637 * @return {@code true} if an only if this method was declared to 638 * take a variable number of arguments. 639 * @since 1.5 640 */ 641 public boolean isVarArgs() { 642 return (getModifiers() & Modifier.VARARGS) != 0; 643 } 644 645 /** 646 * Returns {@code true} if this method is a synthetic 647 * method; returns {@code false} otherwise. 648 * 649 * @return true if and only if this method is a synthetic 650 * method as defined by the Java Language Specification. 651 * @since 1.5 652 */ 653 public boolean isSynthetic() { 654 return Modifier.isSynthetic(getModifiers()); 655 } 656 657 // NOTE that there is no synchronization used here. It is correct 658 // (though not efficient) to generate more than one MethodAccessor 659 // for a given Method. However, avoiding synchronization will 660 // probably make the implementation more scalable. 661 private void acquireMethodAccessor() { 662 // First check to see if one has been created yet, and take it 663 // if so 664 MethodAccessor tmp = null; 665 if (root != null) tmp = root.getMethodAccessor(); 666 if (tmp != null) { 667 methodAccessor = tmp; 668 return; 669 } 670 // Otherwise fabricate one and propagate it up to the root 671 tmp = reflectionFactory.newMethodAccessor(this); 672 setMethodAccessor(tmp); 673 } 674 675 // Returns MethodAccessor for this Method object, not looking up 676 // the chain to the root 677 MethodAccessor getMethodAccessor() { 678 return methodAccessor; 679 } 680 681 // Sets the MethodAccessor for this Method object and 682 // (recursively) its root 683 void setMethodAccessor(MethodAccessor accessor) { 684 methodAccessor = accessor; 685 // Propagate up 686 if (root != null) { 687 root.setMethodAccessor(accessor); 688 } 689 } 690 691 /** 692 * @throws NullPointerException {@inheritDoc} 693 * @since 1.5 694 */ 695 public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { 696 if (annotationClass == null) 697 throw new NullPointerException(); 698 699 return (T) declaredAnnotations().get(annotationClass); 700 } 701 702 /** 703 * @since 1.5 704 */ 705 public Annotation[] getDeclaredAnnotations() { 706 return AnnotationParser.toArray(declaredAnnotations()); 707 } 708 709 private transient Map<Class, Annotation> declaredAnnotations; 710 711 private synchronized Map<Class, Annotation> declaredAnnotations() { 712 if (declaredAnnotations == null) { 713 declaredAnnotations = AnnotationParser.parseAnnotations( 714 annotations, sun.misc.SharedSecrets.getJavaLangAccess(). 715 getConstantPool(getDeclaringClass()), 716 getDeclaringClass()); 717 } 718 return declaredAnnotations; 719 } 720 721 /** 722 * Returns the default value for the annotation member represented by 723 * this {@code Method} instance. If the member is of a primitive type, 724 * an instance of the corresponding wrapper type is returned. Returns 725 * null if no default is associated with the member, or if the method 726 * instance does not represent a declared member of an annotation type. 727 * 728 * @return the default value for the annotation member represented 729 * by this {@code Method} instance. 730 * @throws TypeNotPresentException if the annotation is of type 731 * {@link Class} and no definition can be found for the 732 * default class value. 733 * @since 1.5 734 */ 735 public Object getDefaultValue() { 736 if (annotationDefault == null) 737 return null; 738 Class memberType = AnnotationType.invocationHandlerReturnType( 739 getReturnType()); 740 Object result = AnnotationParser.parseMemberValue( 741 memberType, ByteBuffer.wrap(annotationDefault), 742 sun.misc.SharedSecrets.getJavaLangAccess(). 743 getConstantPool(getDeclaringClass()), 744 getDeclaringClass()); 745 if (result instanceof sun.reflect.annotation.ExceptionProxy) 746 throw new AnnotationFormatError("Invalid default: " + this); 747 return result; 748 } 749 750 /** 751 * Returns an array of arrays that represent the annotations on the formal 752 * parameters, in declaration order, of the method represented by 753 * this {@code Method} object. (Returns an array of length zero if the 754 * underlying method is parameterless. If the method has one or more 755 * parameters, a nested array of length zero is returned for each parameter 756 * with no annotations.) The annotation objects contained in the returned 757 * arrays are serializable. The caller of this method is free to modify 758 * the returned arrays; it will have no effect on the arrays returned to 759 * other callers. 760 * 761 * @return an array of arrays that represent the annotations on the formal 762 * parameters, in declaration order, of the method represented by this 763 * Method object 764 * @since 1.5 765 */ 766 public Annotation[][] getParameterAnnotations() { 767 int numParameters = parameterTypes.length; 768 if (parameterAnnotations == null) 769 return new Annotation[numParameters][0]; 770 771 Annotation[][] result = AnnotationParser.parseParameterAnnotations( 772 parameterAnnotations, 773 sun.misc.SharedSecrets.getJavaLangAccess(). 774 getConstantPool(getDeclaringClass()), 775 getDeclaringClass()); 776 if (result.length != numParameters) 777 throw new java.lang.annotation.AnnotationFormatError( 778 "Parameter annotations don't match number of parameters"); 779 return result; 780 } 781 }