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