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