1 /*
   2  * Copyright (c) 1996, 2006, 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.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 type variable or a parameterized
 321      * type, it is created. Otherwise, it is resolved.
 322      *
 323      * @return an array of Types that represent the exception types
 324      *     thrown by the underlying method
 325      * @throws GenericSignatureFormatError
 326      *     if the generic method signature does not conform to the format
 327      *     specified in the Java Virtual Machine Specification, 3rd edition
 328      * @throws TypeNotPresentException if the underlying method's
 329      *     {@code throws} clause refers to a non-existent type declaration
 330      * @throws MalformedParameterizedTypeException if
 331      *     the underlying method's {@code throws} clause refers to a
 332      *     parameterized type that cannot be instantiated for any reason
 333      * @since 1.5
 334      */
 335       public Type[] getGenericExceptionTypes() {
 336           Type[] result;
 337           if (getGenericSignature() != null &&
 338               ((result = getGenericInfo().getExceptionTypes()).length > 0))
 339               return result;
 340           else
 341               return getExceptionTypes();
 342       }
 343 
 344     /**
 345      * Compares this {@code Method} against the specified object.  Returns
 346      * true if the objects are the same.  Two {@code Methods} are the same if
 347      * they were declared by the same class and have the same name
 348      * and formal parameter types and return type.
 349      */
 350     public boolean equals(Object obj) {
 351         if (obj != null && obj instanceof Method) {
 352             Method other = (Method)obj;
 353             if ((getDeclaringClass() == other.getDeclaringClass())
 354                 && (getName() == other.getName())) {
 355                 if (!returnType.equals(other.getReturnType()))
 356                     return false;
 357                 /* Avoid unnecessary cloning */
 358                 Class<?>[] params1 = parameterTypes;
 359                 Class<?>[] params2 = other.parameterTypes;
 360                 if (params1.length == params2.length) {
 361                     for (int i = 0; i < params1.length; i++) {
 362                         if (params1[i] != params2[i])
 363                             return false;
 364                     }
 365                     return true;
 366                 }
 367             }
 368         }
 369         return false;
 370     }
 371 
 372     /**
 373      * Returns a hashcode for this {@code Method}.  The hashcode is computed
 374      * as the exclusive-or of the hashcodes for the underlying
 375      * method's declaring class name and the method's name.
 376      */
 377     public int hashCode() {
 378         return getDeclaringClass().getName().hashCode() ^ getName().hashCode();
 379     }
 380 
 381     /**
 382      * Returns a string describing this {@code Method}.  The string is
 383      * formatted as the method access modifiers, if any, followed by
 384      * the method return type, followed by a space, followed by the
 385      * class declaring the method, followed by a period, followed by
 386      * the method name, followed by a parenthesized, comma-separated
 387      * list of the method's formal parameter types. If the method
 388      * throws checked exceptions, the parameter list is followed by a
 389      * space, followed by the word throws followed by a
 390      * comma-separated list of the thrown exception types.
 391      * For example:
 392      * <pre>
 393      *    public boolean java.lang.Object.equals(java.lang.Object)
 394      * </pre>
 395      *
 396      * <p>The access modifiers are placed in canonical order as
 397      * specified by "The Java Language Specification".  This is
 398      * {@code public}, {@code protected} or {@code private} first,
 399      * and then other modifiers in the following order:
 400      * {@code abstract}, {@code static}, {@code final},
 401      * {@code synchronized}, {@code native}, {@code strictfp}.
 402      */
 403     public String toString() {
 404         try {
 405             StringBuffer sb = new StringBuffer();
 406             int mod = getModifiers() & Modifier.methodModifiers();
 407             if (mod != 0) {
 408                 sb.append(Modifier.toString(mod) + " ");
 409             }
 410             sb.append(Field.getTypeName(getReturnType()) + " ");
 411             sb.append(Field.getTypeName(getDeclaringClass()) + ".");
 412             sb.append(getName() + "(");
 413             Class<?>[] params = parameterTypes; // avoid clone
 414             for (int j = 0; j < params.length; j++) {
 415                 sb.append(Field.getTypeName(params[j]));
 416                 if (j < (params.length - 1))
 417                     sb.append(",");
 418             }
 419             sb.append(")");
 420             Class<?>[] exceptions = exceptionTypes; // avoid clone
 421             if (exceptions.length > 0) {
 422                 sb.append(" throws ");
 423                 for (int k = 0; k < exceptions.length; k++) {
 424                     sb.append(exceptions[k].getName());
 425                     if (k < (exceptions.length - 1))
 426                         sb.append(",");
 427                 }
 428             }
 429             return sb.toString();
 430         } catch (Exception e) {
 431             return "<" + e + ">";
 432         }
 433     }
 434 
 435     /**
 436      * Returns a string describing this {@code Method}, including
 437      * type parameters.  The string is formatted as the method access
 438      * modifiers, if any, followed by an angle-bracketed
 439      * comma-separated list of the method's type parameters, if any,
 440      * followed by the method's generic return type, followed by a
 441      * space, followed by the class declaring the method, followed by
 442      * a period, followed by the method name, followed by a
 443      * parenthesized, comma-separated list of the method's generic
 444      * formal parameter types.
 445      *
 446      * If this method was declared to take a variable number of
 447      * arguments, instead of denoting the last parameter as
 448      * "<tt><i>Type</i>[]</tt>", it is denoted as
 449      * "<tt><i>Type</i>...</tt>".
 450      *
 451      * A space is used to separate access modifiers from one another
 452      * and from the type parameters or return type.  If there are no
 453      * type parameters, the type parameter list is elided; if the type
 454      * parameter list is present, a space separates the list from the
 455      * class name.  If the method is declared to throw exceptions, the
 456      * parameter list is followed by a space, followed by the word
 457      * throws followed by a comma-separated list of the generic thrown
 458      * exception types.  If there are no type parameters, the type
 459      * parameter list is elided.
 460      *
 461      * <p>The access modifiers are placed in canonical order as
 462      * specified by "The Java Language Specification".  This is
 463      * {@code public}, {@code protected} or {@code private} first,
 464      * and then other modifiers in the following order:
 465      * {@code abstract}, {@code static}, {@code final},
 466      * {@code synchronized}, {@code native}, {@code strictfp}.
 467      *
 468      * @return a string describing this {@code Method},
 469      * include type parameters
 470      *
 471      * @since 1.5
 472      */
 473     public String toGenericString() {
 474         try {
 475             StringBuilder sb = new StringBuilder();
 476             int mod = getModifiers() & Modifier.methodModifiers();
 477             if (mod != 0) {
 478                 sb.append(Modifier.toString(mod) + " ");
 479             }
 480             TypeVariable<?>[] typeparms = getTypeParameters();
 481             if (typeparms.length > 0) {
 482                 boolean first = true;
 483                 sb.append("<");
 484                 for(TypeVariable<?> typeparm: typeparms) {
 485                     if (!first)
 486                         sb.append(",");
 487                     // Class objects can't occur here; no need to test
 488                     // and call Class.getName().
 489                     sb.append(typeparm.toString());
 490                     first = false;
 491                 }
 492                 sb.append("> ");
 493             }
 494 
 495             Type genRetType = getGenericReturnType();
 496             sb.append( ((genRetType instanceof Class<?>)?
 497                         Field.getTypeName((Class<?>)genRetType):genRetType.toString())  + " ");
 498 
 499             sb.append(Field.getTypeName(getDeclaringClass()) + ".");
 500             sb.append(getName() + "(");
 501             Type[] params = getGenericParameterTypes();
 502             for (int j = 0; j < params.length; j++) {
 503                 String param = (params[j] instanceof Class)?
 504                     Field.getTypeName((Class)params[j]):
 505                     (params[j].toString());
 506                 if (isVarArgs() && (j == params.length - 1)) // replace T[] with T...
 507                     param = param.replaceFirst("\\[\\]$", "...");
 508                 sb.append(param);
 509                 if (j < (params.length - 1))
 510                     sb.append(",");
 511             }
 512             sb.append(")");
 513             Type[] exceptions = getGenericExceptionTypes();
 514             if (exceptions.length > 0) {
 515                 sb.append(" throws ");
 516                 for (int k = 0; k < exceptions.length; k++) {
 517                     sb.append((exceptions[k] instanceof Class)?
 518                               ((Class)exceptions[k]).getName():
 519                               exceptions[k].toString());
 520                     if (k < (exceptions.length - 1))
 521                         sb.append(",");
 522                 }
 523             }
 524             return sb.toString();
 525         } catch (Exception e) {
 526             return "<" + e + ">";
 527         }
 528     }
 529 
 530     /**
 531      * Invokes the underlying method represented by this {@code Method}
 532      * object, on the specified object with the specified parameters.
 533      * Individual parameters are automatically unwrapped to match
 534      * primitive formal parameters, and both primitive and reference
 535      * parameters are subject to method invocation conversions as
 536      * necessary.
 537      *
 538      * <p>If the underlying method is static, then the specified {@code obj}
 539      * argument is ignored. It may be null.
 540      *
 541      * <p>If the number of formal parameters required by the underlying method is
 542      * 0, the supplied {@code args} array may be of length 0 or null.
 543      *
 544      * <p>If the underlying method is an instance method, it is invoked
 545      * using dynamic method lookup as documented in The Java Language
 546      * Specification, Second Edition, section 15.12.4.4; in particular,
 547      * overriding based on the runtime type of the target object will occur.
 548      *
 549      * <p>If the underlying method is static, the class that declared
 550      * the method is initialized if it has not already been initialized.
 551      *
 552      * <p>If the method completes normally, the value it returns is
 553      * returned to the caller of invoke; if the value has a primitive
 554      * type, it is first appropriately wrapped in an object. However,
 555      * if the value has the type of an array of a primitive type, the
 556      * elements of the array are <i>not</i> wrapped in objects; in
 557      * other words, an array of primitive type is returned.  If the
 558      * underlying method return type is void, the invocation returns
 559      * null.
 560      *
 561      * @param obj  the object the underlying method is invoked from
 562      * @param args the arguments used for the method call
 563      * @return the result of dispatching the method represented by
 564      * this object on {@code obj} with parameters
 565      * {@code args}
 566      *
 567      * @exception IllegalAccessException    if this {@code Method} object
 568      *              is enforcing Java language access control and the underlying
 569      *              method is inaccessible.
 570      * @exception IllegalArgumentException  if the method is an
 571      *              instance method and the specified object argument
 572      *              is not an instance of the class or interface
 573      *              declaring the underlying method (or of a subclass
 574      *              or implementor thereof); if the number of actual
 575      *              and formal parameters differ; if an unwrapping
 576      *              conversion for primitive arguments fails; or if,
 577      *              after possible unwrapping, a parameter value
 578      *              cannot be converted to the corresponding formal
 579      *              parameter type by a method invocation conversion.
 580      * @exception InvocationTargetException if the underlying method
 581      *              throws an exception.
 582      * @exception NullPointerException      if the specified object is null
 583      *              and the method is an instance method.
 584      * @exception ExceptionInInitializerError if the initialization
 585      * provoked by this method fails.
 586      */
 587     public Object invoke(Object obj, Object... args)
 588         throws IllegalAccessException, IllegalArgumentException,
 589            InvocationTargetException
 590     {
 591         if (!override) {
 592             if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
 593                 Class<?> caller = Reflection.getCallerClass(1);
 594                 Class<?> targetClass = ((obj == null || !Modifier.isProtected(modifiers))
 595                                         ? clazz
 596                                         : obj.getClass());
 597 
 598                 boolean cached;
 599                 synchronized (this) {
 600                     cached = (securityCheckCache == caller)
 601                             && (securityCheckTargetClassCache == targetClass);
 602                 }
 603                 if (!cached) {
 604                     Reflection.ensureMemberAccess(caller, clazz, obj, modifiers);
 605                     synchronized (this) {
 606                         securityCheckCache = caller;
 607                         securityCheckTargetClassCache = targetClass;
 608                     }
 609                 }
 610             }
 611         }
 612         if (methodAccessor == null) acquireMethodAccessor();
 613         return methodAccessor.invoke(obj, args);
 614     }
 615 
 616     /**
 617      * Returns {@code true} if this method is a bridge
 618      * method; returns {@code false} otherwise.
 619      *
 620      * @return true if and only if this method is a bridge
 621      * method as defined by the Java Language Specification.
 622      * @since 1.5
 623      */
 624     public boolean isBridge() {
 625         return (getModifiers() & Modifier.BRIDGE) != 0;
 626     }
 627 
 628     /**
 629      * Returns {@code true} if this method was declared to take
 630      * a variable number of arguments; returns {@code false}
 631      * otherwise.
 632      *
 633      * @return {@code true} if an only if this method was declared to
 634      * take a variable number of arguments.
 635      * @since 1.5
 636      */
 637     public boolean isVarArgs() {
 638         return (getModifiers() & Modifier.VARARGS) != 0;
 639     }
 640 
 641     /**
 642      * Returns {@code true} if this method is a synthetic
 643      * method; returns {@code false} otherwise.
 644      *
 645      * @return true if and only if this method is a synthetic
 646      * method as defined by the Java Language Specification.
 647      * @since 1.5
 648      */
 649     public boolean isSynthetic() {
 650         return Modifier.isSynthetic(getModifiers());
 651     }
 652 
 653     // NOTE that there is no synchronization used here. It is correct
 654     // (though not efficient) to generate more than one MethodAccessor
 655     // for a given Method. However, avoiding synchronization will
 656     // probably make the implementation more scalable.
 657     private void acquireMethodAccessor() {
 658         // First check to see if one has been created yet, and take it
 659         // if so
 660         MethodAccessor tmp = null;
 661         if (root != null) tmp = root.getMethodAccessor();
 662         if (tmp != null) {
 663             methodAccessor = tmp;
 664             return;
 665         }
 666         // Otherwise fabricate one and propagate it up to the root
 667         tmp = reflectionFactory.newMethodAccessor(this);
 668         setMethodAccessor(tmp);
 669     }
 670 
 671     // Returns MethodAccessor for this Method object, not looking up
 672     // the chain to the root
 673     MethodAccessor getMethodAccessor() {
 674         return methodAccessor;
 675     }
 676 
 677     // Sets the MethodAccessor for this Method object and
 678     // (recursively) its root
 679     void setMethodAccessor(MethodAccessor accessor) {
 680         methodAccessor = accessor;
 681         // Propagate up
 682         if (root != null) {
 683             root.setMethodAccessor(accessor);
 684         }
 685     }
 686 
 687     /**
 688      * @throws NullPointerException {@inheritDoc}
 689      * @since 1.5
 690      */
 691     public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
 692         if (annotationClass == null)
 693             throw new NullPointerException();
 694 
 695         return (T) declaredAnnotations().get(annotationClass);
 696     }
 697 
 698     /**
 699      * @since 1.5
 700      */
 701     public Annotation[] getDeclaredAnnotations()  {
 702         return AnnotationParser.toArray(declaredAnnotations());
 703     }
 704 
 705     private transient Map<Class<? extends Annotation>, Annotation> declaredAnnotations;
 706 
 707     private synchronized  Map<Class<? extends Annotation>, Annotation> declaredAnnotations() {
 708         if (declaredAnnotations == null) {
 709             declaredAnnotations = AnnotationParser.parseAnnotations(
 710                 annotations, sun.misc.SharedSecrets.getJavaLangAccess().
 711                 getConstantPool(getDeclaringClass()),
 712                 getDeclaringClass());
 713         }
 714         return declaredAnnotations;
 715     }
 716 
 717     /**
 718      * Returns the default value for the annotation member represented by
 719      * this {@code Method} instance.  If the member is of a primitive type,
 720      * an instance of the corresponding wrapper type is returned. Returns
 721      * null if no default is associated with the member, or if the method
 722      * instance does not represent a declared member of an annotation type.
 723      *
 724      * @return the default value for the annotation member represented
 725      *     by this {@code Method} instance.
 726      * @throws TypeNotPresentException if the annotation is of type
 727      *     {@link Class} and no definition can be found for the
 728      *     default class value.
 729      * @since  1.5
 730      */
 731     public Object getDefaultValue() {
 732         if  (annotationDefault == null)
 733             return null;
 734         Class<?> memberType = AnnotationType.invocationHandlerReturnType(
 735             getReturnType());
 736         Object result = AnnotationParser.parseMemberValue(
 737             memberType, ByteBuffer.wrap(annotationDefault),
 738             sun.misc.SharedSecrets.getJavaLangAccess().
 739                 getConstantPool(getDeclaringClass()),
 740             getDeclaringClass());
 741         if (result instanceof sun.reflect.annotation.ExceptionProxy)
 742             throw new AnnotationFormatError("Invalid default: " + this);
 743         return result;
 744     }
 745 
 746     /**
 747      * Returns an array of arrays that represent the annotations on the formal
 748      * parameters, in declaration order, of the method represented by
 749      * this {@code Method} object. (Returns an array of length zero if the
 750      * underlying method is parameterless.  If the method has one or more
 751      * parameters, a nested array of length zero is returned for each parameter
 752      * with no annotations.) The annotation objects contained in the returned
 753      * arrays are serializable.  The caller of this method is free to modify
 754      * the returned arrays; it will have no effect on the arrays returned to
 755      * other callers.
 756      *
 757      * @return an array of arrays that represent the annotations on the formal
 758      *    parameters, in declaration order, of the method represented by this
 759      *    Method object
 760      * @since 1.5
 761      */
 762     public Annotation[][] getParameterAnnotations() {
 763         int numParameters = parameterTypes.length;
 764         if (parameterAnnotations == null)
 765             return new Annotation[numParameters][0];
 766 
 767         Annotation[][] result = AnnotationParser.parseParameterAnnotations(
 768             parameterAnnotations,
 769             sun.misc.SharedSecrets.getJavaLangAccess().
 770                 getConstantPool(getDeclaringClass()),
 771             getDeclaringClass());
 772         if (result.length != numParameters)
 773             throw new java.lang.annotation.AnnotationFormatError(
 774                 "Parameter annotations don't match number of parameters");
 775         return result;
 776     }
 777 }