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