1 /*
   2  * Copyright (c) 2012, 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 java.lang.annotation.*;
  29 import java.util.Map;
  30 import java.util.Objects;
  31 import sun.reflect.annotation.AnnotationParser;
  32 import sun.reflect.annotation.AnnotationSupport;
  33 import sun.reflect.annotation.TypeAnnotationParser;
  34 import sun.reflect.annotation.TypeAnnotation;
  35 import sun.reflect.generics.repository.ConstructorRepository;
  36 
  37 /**
  38  * A shared superclass for the common functionality of {@link Method}
  39  * and {@link Constructor}.
  40  *
  41  * @since 1.8
  42  */
  43 public abstract class Executable extends AccessibleObject
  44     implements Member, GenericDeclaration {
  45     /*
  46      * Only grant package-visibility to the constructor.
  47      */
  48     Executable() {}
  49 
  50     /**
  51      * Accessor method to allow code sharing
  52      */
  53     abstract byte[] getAnnotationBytes();
  54     abstract byte[] getTypeAnnotationBytes();
  55 
  56     /**
  57      * Does the Executable have generic information.
  58      */
  59     abstract boolean hasGenericInformation();
  60 
  61     abstract ConstructorRepository getGenericInfo();
  62 
  63     boolean equalParamTypes(Class<?>[] params1, Class<?>[] params2) {
  64         /* Avoid unnecessary cloning */
  65         if (params1.length == params2.length) {
  66             for (int i = 0; i < params1.length; i++) {
  67                 if (params1[i] != params2[i])
  68                     return false;
  69             }
  70             return true;
  71         }
  72         return false;
  73     }
  74 
  75     Annotation[][] parseParameterAnnotations(byte[] parameterAnnotations) {
  76         return AnnotationParser.parseParameterAnnotations(
  77                parameterAnnotations,
  78                sun.misc.SharedSecrets.getJavaLangAccess().
  79                getConstantPool(getDeclaringClass()),
  80                getDeclaringClass());
  81     }
  82 
  83     void separateWithCommas(Class<?>[] types, StringBuilder sb) {
  84         for (int j = 0; j < types.length; j++) {
  85             sb.append(types[j].getTypeName());
  86             if (j < (types.length - 1))
  87                 sb.append(",");
  88         }
  89 
  90     }
  91 
  92     void printModifiersIfNonzero(StringBuilder sb, int mask, boolean isDefault) {
  93         int mod = getModifiers() & mask;
  94 
  95         if (mod != 0 && !isDefault) {
  96             sb.append(Modifier.toString(mod)).append(' ');
  97         } else {
  98             int access_mod = mod & Modifier.ACCESS_MODIFIERS;
  99             if (access_mod != 0)
 100                 sb.append(Modifier.toString(access_mod)).append(' ');
 101             if (isDefault)
 102                 sb.append("default ");
 103             mod = (mod & ~Modifier.ACCESS_MODIFIERS);
 104             if (mod != 0)
 105                 sb.append(Modifier.toString(mod)).append(' ');
 106         }
 107     }
 108 
 109     String sharedToString(int modifierMask,
 110                           boolean isDefault,
 111                           Class<?>[] parameterTypes,
 112                           Class<?>[] exceptionTypes) {
 113         try {
 114             StringBuilder sb = new StringBuilder();
 115 
 116             printModifiersIfNonzero(sb, modifierMask, isDefault);
 117             specificToStringHeader(sb);
 118 
 119             sb.append('(');
 120             separateWithCommas(parameterTypes, sb);
 121             sb.append(')');
 122             if (exceptionTypes.length > 0) {
 123                 sb.append(" throws ");
 124                 separateWithCommas(exceptionTypes, sb);
 125             }
 126             return sb.toString();
 127         } catch (Exception e) {
 128             return "<" + e + ">";
 129         }
 130     }
 131 
 132     /**
 133      * Generate toString header information specific to a method or
 134      * constructor.
 135      */
 136     abstract void specificToStringHeader(StringBuilder sb);
 137 
 138     String sharedToGenericString(int modifierMask, boolean isDefault) {
 139         try {
 140             StringBuilder sb = new StringBuilder();
 141 
 142             printModifiersIfNonzero(sb, modifierMask, isDefault);
 143 
 144             TypeVariable<?>[] typeparms = getTypeParameters();
 145             if (typeparms.length > 0) {
 146                 boolean first = true;
 147                 sb.append('<');
 148                 for(TypeVariable<?> typeparm: typeparms) {
 149                     if (!first)
 150                         sb.append(',');
 151                     // Class objects can't occur here; no need to test
 152                     // and call Class.getName().
 153                     sb.append(typeparm.toString());
 154                     first = false;
 155                 }
 156                 sb.append("> ");
 157             }
 158 
 159             specificToGenericStringHeader(sb);
 160 
 161             sb.append('(');
 162             Type[] params = getGenericParameterTypes();
 163             for (int j = 0; j < params.length; j++) {
 164                 String param = params[j].getTypeName();
 165                 if (isVarArgs() && (j == params.length - 1)) // replace T[] with T...
 166                     param = param.replaceFirst("\\[\\]$", "...");
 167                 sb.append(param);
 168                 if (j < (params.length - 1))
 169                     sb.append(',');
 170             }
 171             sb.append(')');
 172             Type[] exceptions = getGenericExceptionTypes();
 173             if (exceptions.length > 0) {
 174                 sb.append(" throws ");
 175                 for (int k = 0; k < exceptions.length; k++) {
 176                     sb.append((exceptions[k] instanceof Class)?
 177                               ((Class)exceptions[k]).getName():
 178                               exceptions[k].toString());
 179                     if (k < (exceptions.length - 1))
 180                         sb.append(',');
 181                 }
 182             }
 183             return sb.toString();
 184         } catch (Exception e) {
 185             return "<" + e + ">";
 186         }
 187     }
 188 
 189     /**
 190      * Generate toGenericString header information specific to a
 191      * method or constructor.
 192      */
 193     abstract void specificToGenericStringHeader(StringBuilder sb);
 194 
 195     /**
 196      * Returns the {@code Class} object representing the class or interface
 197      * that declares the executable represented by this object.
 198      */
 199     public abstract Class<?> getDeclaringClass();
 200 
 201     /**
 202      * Returns the name of the executable represented by this object.
 203      */
 204     public abstract String getName();
 205 
 206     /**
 207      * Returns the Java language {@linkplain Modifier modifiers} for
 208      * the executable represented by this object.
 209      */
 210     public abstract int getModifiers();
 211 
 212     /**
 213      * Returns an array of {@code TypeVariable} objects that represent the
 214      * type variables declared by the generic declaration represented by this
 215      * {@code GenericDeclaration} object, in declaration order.  Returns an
 216      * array of length 0 if the underlying generic declaration declares no type
 217      * variables.
 218      *
 219      * @return an array of {@code TypeVariable} objects that represent
 220      *     the type variables declared by this generic declaration
 221      * @throws GenericSignatureFormatError if the generic
 222      *     signature of this generic declaration does not conform to
 223      *     the format specified in
 224      *     <cite>The Java&trade; Virtual Machine Specification</cite>
 225      */
 226     public abstract TypeVariable<?>[] getTypeParameters();
 227 
 228     /**
 229      * Returns an array of {@code Class} objects that represent the formal
 230      * parameter types, in declaration order, of the executable
 231      * represented by this object.  Returns an array of length
 232      * 0 if the underlying executable takes no parameters.
 233      *
 234      * @return the parameter types for the executable this object
 235      * represents
 236      */
 237     public abstract Class<?>[] getParameterTypes();
 238 
 239     /**
 240      * Returns the number of formal parameters (whether explicitly
 241      * declared or implicitly declared or neither) for the executable
 242      * represented by this object.
 243      *
 244      * @return The number of formal parameters for the executable this
 245      * object represents
 246      */
 247     public int getParameterCount() {
 248         throw new AbstractMethodError();
 249     }
 250 
 251     /**
 252      * Returns an array of {@code Type} objects that represent the formal
 253      * parameter types, in declaration order, of the executable represented by
 254      * this object. Returns an array of length 0 if the
 255      * underlying executable takes no parameters.
 256      *
 257      * <p>If a formal parameter type is a parameterized type,
 258      * the {@code Type} object returned for it must accurately reflect
 259      * the actual type parameters used in the source code.
 260      *
 261      * <p>If a formal parameter type is a type variable or a parameterized
 262      * type, it is created. Otherwise, it is resolved.
 263      *
 264      * @return an array of {@code Type}s that represent the formal
 265      *     parameter types of the underlying executable, in declaration order
 266      * @throws GenericSignatureFormatError
 267      *     if the generic method signature does not conform to the format
 268      *     specified in
 269      *     <cite>The Java&trade; Virtual Machine Specification</cite>
 270      * @throws TypeNotPresentException if any of the parameter
 271      *     types of the underlying executable refers to a non-existent type
 272      *     declaration
 273      * @throws MalformedParameterizedTypeException if any of
 274      *     the underlying executable's parameter types refer to a parameterized
 275      *     type that cannot be instantiated for any reason
 276      */
 277     public Type[] getGenericParameterTypes() {
 278         if (hasGenericInformation())
 279             return getGenericInfo().getParameterTypes();
 280         else
 281             return getParameterTypes();
 282     }
 283 
 284     /**
 285      * Returns an array of {@code Parameter} objects that represent
 286      * all the parameters to the underlying executable represented by
 287      * this object.  Returns an array of length 0 if the executable
 288      * has no parameters.
 289      *
 290      * The parameters of the underlying executable do not necessarily
 291      * have unique names, or names that are legal identifiers in the
 292      * Java programming language (JLS 3.8).
 293      *
 294      * @return an array of {@code Parameter} objects representing all
 295      * the parameters to the executable this object represents
 296      */
 297     public Parameter[] getParameters() {
 298         // TODO: This may eventually need to be guarded by security
 299         // mechanisms similar to those in Field, Method, etc.
 300         //
 301         // Need to copy the cached array to prevent users from messing
 302         // with it.  Since parameters are immutable, we can
 303         // shallow-copy.
 304         return privateGetParameters().clone();
 305     }
 306 
 307     private Parameter[] synthesizeAllParams() {
 308         final int realparams = getParameterCount();
 309         final Parameter[] out = new Parameter[realparams];
 310         for (int i = 0; i < realparams; i++)
 311             // TODO: is there a way to synthetically derive the
 312             // modifiers?  Probably not in the general case, since
 313             // we'd have no way of knowing about them, but there
 314             // may be specific cases.
 315             out[i] = new Parameter("arg" + i, 0, this, i);
 316         return out;
 317     }
 318 
 319     private Parameter[] privateGetParameters() {
 320         // Use tmp to avoid multiple writes to a volatile.
 321         Parameter[] tmp = parameters;
 322 
 323         if (tmp == null) {
 324 
 325             // Otherwise, go to the JVM to get them
 326             tmp = getParameters0();
 327 
 328             // If we get back nothing, then synthesize parameters
 329             if (tmp == null) {
 330                 hasRealParameterData = false;
 331                 tmp = synthesizeAllParams();
 332             } else {
 333                 hasRealParameterData = true;
 334             }
 335 
 336             parameters = tmp;
 337         }
 338 
 339         return tmp;
 340     }
 341 
 342     boolean hasRealParameterData() {
 343         // If this somehow gets called before parameters gets
 344         // initialized, force it into existence.
 345         if (parameters == null)
 346             privateGetParameters();
 347 
 348         return hasRealParameterData;
 349     }
 350 
 351     private boolean hasRealParameterData;
 352     private transient volatile Parameter[] parameters;
 353 
 354     private native Parameter[] getParameters0();
 355 
 356     /**
 357      * Returns an array of {@code Class} objects that represent the
 358      * types of exceptions declared to be thrown by the underlying
 359      * executable represented by this object.  Returns an array of
 360      * length 0 if the executable declares no exceptions in its {@code
 361      * throws} clause.
 362      *
 363      * @return the exception types declared as being thrown by the
 364      * executable this object represents
 365      */
 366     public abstract Class<?>[] getExceptionTypes();
 367 
 368     /**
 369      * Returns an array of {@code Type} objects that represent the
 370      * exceptions declared to be thrown by this executable object.
 371      * Returns an array of length 0 if the underlying executable declares
 372      * no exceptions in its {@code throws} clause.
 373      *
 374      * <p>If an exception type is a type variable or a parameterized
 375      * type, it is created. Otherwise, it is resolved.
 376      *
 377      * @return an array of Types that represent the exception types
 378      *     thrown by the underlying executable
 379      * @throws GenericSignatureFormatError
 380      *     if the generic method signature does not conform to the format
 381      *     specified in
 382      *     <cite>The Java&trade; Virtual Machine Specification</cite>
 383      * @throws TypeNotPresentException if the underlying executable's
 384      *     {@code throws} clause refers to a non-existent type declaration
 385      * @throws MalformedParameterizedTypeException if
 386      *     the underlying executable's {@code throws} clause refers to a
 387      *     parameterized type that cannot be instantiated for any reason
 388      */
 389     public Type[] getGenericExceptionTypes() {
 390         Type[] result;
 391         if (hasGenericInformation() &&
 392             ((result = getGenericInfo().getExceptionTypes()).length > 0))
 393             return result;
 394         else
 395             return getExceptionTypes();
 396     }
 397 
 398     /**
 399      * Returns a string describing this {@code Executable}, including
 400      * any type parameters.
 401      */
 402     public abstract String toGenericString();
 403 
 404     /**
 405      * Returns {@code true} if this executable was declared to take a
 406      * variable number of arguments; returns {@code false} otherwise.
 407      *
 408      * @return {@code true} if an only if this executable was declared
 409      * to take a variable number of arguments.
 410      */
 411     public boolean isVarArgs()  {
 412         return (getModifiers() & Modifier.VARARGS) != 0;
 413     }
 414 
 415     /**
 416      * Returns {@code true} if this executable is a synthetic
 417      * construct; returns {@code false} otherwise.
 418      *
 419      * @return true if and only if this executable is a synthetic
 420      * construct as defined by
 421      * <cite>The Java&trade; Language Specification</cite>.
 422      * @jls 13.1 The Form of a Binary
 423      */
 424     public boolean isSynthetic() {
 425         return Modifier.isSynthetic(getModifiers());
 426     }
 427 
 428     /**
 429      * Returns an array of arrays that represent the annotations on
 430      * the formal parameters, in declaration order, of the executable
 431      * represented by this object. (Returns an array of length zero if
 432      * the underlying executable is parameterless.  If the executable has
 433      * one or more parameters, a nested array of length zero is
 434      * returned for each parameter with no annotations.) The
 435      * annotation objects contained in the returned arrays are
 436      * serializable.  The caller of this method is free to modify the
 437      * returned arrays; it will have no effect on the arrays returned
 438      * to other callers.
 439      *
 440      * @return an array of arrays that represent the annotations on the formal
 441      *    parameters, in declaration order, of the executable represented by this
 442      *    object
 443      */
 444     public abstract Annotation[][] getParameterAnnotations();
 445 
 446     Annotation[][] sharedGetParameterAnnotations(Class<?>[] parameterTypes,
 447                                                  byte[] parameterAnnotations) {
 448         int numParameters = parameterTypes.length;
 449         if (parameterAnnotations == null)
 450             return new Annotation[numParameters][0];
 451 
 452         Annotation[][] result = parseParameterAnnotations(parameterAnnotations);
 453 
 454         if (result.length != numParameters)
 455             handleParameterNumberMismatch(result.length, numParameters);
 456         return result;
 457     }
 458 
 459     abstract void handleParameterNumberMismatch(int resultLength, int numParameters);
 460 
 461     /**
 462      * {@inheritDoc}
 463      * @throws NullPointerException  {@inheritDoc}
 464      */
 465     public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
 466         Objects.requireNonNull(annotationClass);
 467         return annotationClass.cast(declaredAnnotations().get(annotationClass));
 468     }
 469 
 470     /**
 471      * {@inheritDoc}
 472      * @throws NullPointerException {@inheritDoc}
 473      * @since 1.8
 474      */
 475     @Override
 476     public <T extends Annotation> T[] getAnnotationsByType(Class<T> annotationClass) {
 477         Objects.requireNonNull(annotationClass);
 478 
 479         return AnnotationSupport.getMultipleAnnotations(declaredAnnotations(), annotationClass);
 480     }
 481 
 482     /**
 483      * {@inheritDoc}
 484      */
 485     public Annotation[] getDeclaredAnnotations()  {
 486         return AnnotationParser.toArray(declaredAnnotations());
 487     }
 488 
 489     private transient Map<Class<? extends Annotation>, Annotation> declaredAnnotations;
 490 
 491     private synchronized  Map<Class<? extends Annotation>, Annotation> declaredAnnotations() {
 492         if (declaredAnnotations == null) {
 493             declaredAnnotations = AnnotationParser.parseAnnotations(
 494                 getAnnotationBytes(),
 495                 sun.misc.SharedSecrets.getJavaLangAccess().
 496                 getConstantPool(getDeclaringClass()),
 497                 getDeclaringClass());
 498         }
 499         return declaredAnnotations;
 500     }
 501 
 502     /**
 503      * Returns an AnnotatedType object that represents the use of a type to
 504      * specify the return type of the method/constructor represented by this
 505      * Executable.
 506      *
 507      * If this Executable represents a constructor, the AnnotatedType object
 508      * represents the type of the constructed object.
 509      *
 510      * If this Executable represents a method, the AnnotatedType object
 511      * represents the use of a type to specify the return type of the method.
 512      *
 513      * @since 1.8
 514      */
 515     public abstract AnnotatedType getAnnotatedReturnType();
 516 
 517     /* Helper for subclasses of Executable.
 518      *
 519      * Returns an AnnotatedType object that represents the use of a type to
 520      * specify the return type of the method/constructor represented by this
 521      * Executable.
 522      *
 523      * @since 1.8
 524      */
 525     AnnotatedType getAnnotatedReturnType0(Type returnType) {
 526         return TypeAnnotationParser.buildAnnotatedType(getTypeAnnotationBytes(),
 527                 sun.misc.SharedSecrets.getJavaLangAccess().
 528                         getConstantPool(getDeclaringClass()),
 529                 this,
 530                 getDeclaringClass(),
 531                 returnType,
 532                 TypeAnnotation.TypeAnnotationTarget.METHOD_RETURN);
 533     }
 534 
 535     /**
 536      * Returns an AnnotatedType object that represents the use of a type to
 537      * specify the receiver type of the method/constructor represented by this
 538      * Executable. The receiver type of a method/constructor is available only
 539      * if the method/constructor declares a formal parameter called 'this'.
 540      *
 541      * Returns null if this Executable represents a constructor or instance
 542      * method that either declares no formal parameter called 'this', or
 543      * declares a formal parameter called 'this' with no annotations on its
 544      * type.
 545      *
 546      * Returns null if this Executable represents a static method.
 547      *
 548      * @since 1.8
 549      */
 550     public AnnotatedType getAnnotatedReceiverType() {
 551         return TypeAnnotationParser.buildAnnotatedType(getTypeAnnotationBytes(),
 552                 sun.misc.SharedSecrets.getJavaLangAccess().
 553                         getConstantPool(getDeclaringClass()),
 554                 this,
 555                 getDeclaringClass(),
 556                 getDeclaringClass(),
 557                 TypeAnnotation.TypeAnnotationTarget.METHOD_RECEIVER);
 558     }
 559 
 560     /**
 561      * Returns an array of AnnotatedType objects that represent the use of
 562      * types to specify formal parameter types of the method/constructor
 563      * represented by this Executable. The order of the objects in the array
 564      * corresponds to the order of the formal parameter types in the
 565      * declaration of the method/constructor.
 566      *
 567      * Returns an array of length 0 if the method/constructor declares no
 568      * parameters.
 569      *
 570      * @since 1.8
 571      */
 572     public AnnotatedType[] getAnnotatedParameterTypes() {
 573         return TypeAnnotationParser.buildAnnotatedTypes(getTypeAnnotationBytes(),
 574                 sun.misc.SharedSecrets.getJavaLangAccess().
 575                         getConstantPool(getDeclaringClass()),
 576                 this,
 577                 getDeclaringClass(),
 578                 getParameterTypes(),
 579                 TypeAnnotation.TypeAnnotationTarget.METHOD_FORMAL_PARAMETER);
 580     }
 581 
 582     /**
 583      * Returns an array of AnnotatedType objects that represent the use of
 584      * types to specify the declared exceptions of the method/constructor
 585      * represented by this Executable. The order of the objects in the array
 586      * corresponds to the order of the exception types in the declaration of
 587      * the method/constructor.
 588      *
 589      * Returns an array of length 0 if the method/constructor declares no
 590      * exceptions.
 591      *
 592      * @since 1.8
 593      */
 594     public AnnotatedType[] getAnnotatedExceptionTypes() {
 595         return TypeAnnotationParser.buildAnnotatedTypes(getTypeAnnotationBytes(),
 596                 sun.misc.SharedSecrets.getJavaLangAccess().
 597                         getConstantPool(getDeclaringClass()),
 598                 this,
 599                 getDeclaringClass(),
 600                 getGenericExceptionTypes(),
 601                 TypeAnnotation.TypeAnnotationTarget.THROWS);
 602     }
 603 
 604 }