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