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