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 jdk.internal.misc.SharedSecrets;
  29 import jdk.internal.reflect.CallerSensitive;
  30 import jdk.internal.reflect.ConstructorAccessor;
  31 import jdk.internal.reflect.Reflection;
  32 import jdk.internal.vm.annotation.ForceInline;
  33 import sun.reflect.annotation.TypeAnnotation;
  34 import sun.reflect.annotation.TypeAnnotationParser;
  35 import sun.reflect.generics.repository.ConstructorRepository;
  36 import sun.reflect.generics.factory.CoreReflectionFactory;
  37 import sun.reflect.generics.factory.GenericsFactory;
  38 import sun.reflect.generics.scope.ConstructorScope;
  39 import java.lang.annotation.Annotation;
  40 import java.lang.annotation.AnnotationFormatError;
  41 
  42 /**
  43  * {@code Constructor} provides information about, and access to, a single
  44  * constructor for a class.
  45  *
  46  * <p>{@code Constructor} permits widening conversions to occur when matching the
  47  * actual parameters to newInstance() with the underlying
  48  * constructor's formal parameters, but throws an
  49  * {@code IllegalArgumentException} if a narrowing conversion would occur.
  50  *
  51  * @param <T> the class in which the constructor is declared
  52  *
  53  * @see Member
  54  * @see java.lang.Class
  55  * @see java.lang.Class#getConstructors()
  56  * @see java.lang.Class#getConstructor(Class[])
  57  * @see java.lang.Class#getDeclaredConstructors()
  58  *
  59  * @author      Kenneth Russell
  60  * @author      Nakul Saraiya
  61  */
  62 public final class Constructor<T> extends Executable {
  63     private Class<T>            clazz;
  64     private int                 slot;
  65     private Class<?>[]          parameterTypes;
  66     private Class<?>[]          exceptionTypes;
  67     private int                 modifiers;
  68     // Generics and annotations support
  69     private transient String    signature;
  70     // generic info repository; lazily initialized
  71     private transient ConstructorRepository genericInfo;
  72     private byte[]              annotations;
  73     private byte[]              parameterAnnotations;
  74 
  75     // Generics infrastructure
  76     // Accessor for factory
  77     private GenericsFactory getFactory() {
  78         // create scope and factory
  79         return CoreReflectionFactory.make(this, ConstructorScope.make(this));
  80     }
  81 
  82     // Accessor for generic info repository
  83     @Override
  84     ConstructorRepository getGenericInfo() {
  85         // lazily initialize repository if necessary
  86         if (genericInfo == null) {
  87             // create and cache generic info repository
  88             genericInfo =
  89                 ConstructorRepository.make(getSignature(),
  90                                            getFactory());
  91         }
  92         return genericInfo; //return cached repository
  93     }
  94 
  95     private volatile ConstructorAccessor constructorAccessor;
  96     // For sharing of ConstructorAccessors. This branching structure
  97     // is currently only two levels deep (i.e., one root Constructor
  98     // and potentially many Constructor objects pointing to it.)
  99     //
 100     // If this branching structure would ever contain cycles, deadlocks can
 101     // occur in annotation code.
 102     private Constructor<T>      root;
 103 
 104     /**
 105      * Used by Excecutable for annotation sharing.
 106      */
 107     @Override
 108     Executable getRoot() {
 109         return root;
 110     }
 111 
 112     /**
 113      * Package-private constructor used by ReflectAccess to enable
 114      * instantiation of these objects in Java code from the java.lang
 115      * package via sun.reflect.LangReflectAccess.
 116      */
 117     Constructor(Class<T> declaringClass,
 118                 Class<?>[] parameterTypes,
 119                 Class<?>[] checkedExceptions,
 120                 int modifiers,
 121                 int slot,
 122                 String signature,
 123                 byte[] annotations,
 124                 byte[] parameterAnnotations) {
 125         this.clazz = declaringClass;
 126         this.parameterTypes = parameterTypes;
 127         this.exceptionTypes = checkedExceptions;
 128         this.modifiers = modifiers;
 129         this.slot = slot;
 130         this.signature = signature;
 131         this.annotations = annotations;
 132         this.parameterAnnotations = parameterAnnotations;
 133     }
 134 
 135     /**
 136      * Package-private routine (exposed to java.lang.Class via
 137      * ReflectAccess) which returns a copy of this Constructor. The copy's
 138      * "root" field points to this Constructor.
 139      */
 140     Constructor<T> copy() {
 141         // This routine enables sharing of ConstructorAccessor objects
 142         // among Constructor 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         if (this.root != null)
 149             throw new IllegalArgumentException("Can not copy a non-root Constructor");
 150 
 151         Constructor<T> res = new Constructor<>(clazz,
 152                                                parameterTypes,
 153                                                exceptionTypes, modifiers, slot,
 154                                                signature,
 155                                                annotations,
 156                                                parameterAnnotations);
 157         res.root = this;
 158         // Might as well eagerly propagate this if already present
 159         res.constructorAccessor = constructorAccessor;
 160         return res;
 161     }
 162 
 163     /**
 164      * {@inheritDoc}
 165      *
 166      * <p> A {@code SecurityException} is also thrown if this object is a
 167      * {@code Constructor} object for the class {@code Class} and {@code flag}
 168      * is true. </p>
 169      *
 170      * @param flag {@inheritDoc}
 171      */
 172     @Override
 173     @CallerSensitive
 174     public void setAccessible(boolean flag) {
 175         AccessibleObject.checkPermission();
 176         if (flag) {
 177             checkCanSetAccessible(Reflection.getCallerClass());
 178         }
 179         setAccessible0(flag);
 180     }
 181 
 182     @Override
 183     void checkCanSetAccessible(Class<?> caller) {
 184         checkCanSetAccessible(caller, clazz);
 185         if (clazz == Class.class) {
 186             // can we change this to InaccessibleObjectException?
 187             throw new SecurityException("Cannot make a java.lang.Class"
 188                                         + " constructor accessible");
 189         }
 190     }
 191 
 192     @Override
 193     boolean hasGenericInformation() {
 194         return (getSignature() != null);
 195     }
 196 
 197     @Override
 198     byte[] getAnnotationBytes() {
 199         return annotations;
 200     }
 201 
 202     /**
 203      * {@inheritDoc}
 204      */
 205     @Override
 206     public Class<T> getDeclaringClass() {
 207         return clazz;
 208     }
 209 
 210     /**
 211      * Returns the name of this constructor, as a string.  This is
 212      * the binary name of the constructor's declaring class.
 213      */
 214     @Override
 215     public String getName() {
 216         return getDeclaringClass().getName();
 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<Constructor<T>>[] getTypeParameters() {
 235       if (getSignature() != null) {
 236         return (TypeVariable<Constructor<T>>[])getGenericInfo().getTypeParameters();
 237       } else
 238           return (TypeVariable<Constructor<T>>[])new TypeVariable[0];
 239     }
 240 
 241 
 242     /**
 243      * {@inheritDoc}
 244      */
 245     @Override
 246     public Class<?>[] getParameterTypes() {
 247         return parameterTypes.clone();
 248     }
 249 
 250     /**
 251      * {@inheritDoc}
 252      * @since 1.8
 253      */
 254     public int getParameterCount() { return parameterTypes.length; }
 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     /**
 278      * {@inheritDoc}
 279      * @throws GenericSignatureFormatError {@inheritDoc}
 280      * @throws TypeNotPresentException {@inheritDoc}
 281      * @throws MalformedParameterizedTypeException {@inheritDoc}
 282      * @since 1.5
 283      */
 284     @Override
 285     public Type[] getGenericExceptionTypes() {
 286         return super.getGenericExceptionTypes();
 287     }
 288 
 289     /**
 290      * Compares this {@code Constructor} against the specified object.
 291      * Returns true if the objects are the same.  Two {@code Constructor} objects are
 292      * the same if they were declared by the same class and have the
 293      * same formal parameter types.
 294      */
 295     public boolean equals(Object obj) {
 296         if (obj != null && obj instanceof Constructor) {
 297             Constructor<?> other = (Constructor<?>)obj;
 298             if (getDeclaringClass() == other.getDeclaringClass()) {
 299                 return equalParamTypes(parameterTypes, other.parameterTypes);
 300             }
 301         }
 302         return false;
 303     }
 304 
 305     /**
 306      * Returns a hashcode for this {@code Constructor}. The hashcode is
 307      * the same as the hashcode for the underlying constructor's
 308      * declaring class name.
 309      */
 310     public int hashCode() {
 311         return getDeclaringClass().getName().hashCode();
 312     }
 313 
 314     /**
 315      * Returns a string describing this {@code Constructor}.  The string is
 316      * formatted as the constructor access modifiers, if any,
 317      * followed by the fully-qualified name of the declaring class,
 318      * followed by a parenthesized, comma-separated list of the
 319      * constructor's formal parameter types.  For example:
 320      * <pre>{@code
 321      *    public java.util.Hashtable(int,float)
 322      * }</pre>
 323      *
 324      * <p>The only possible modifiers for constructors are the access
 325      * modifiers {@code public}, {@code protected} or
 326      * {@code private}.  Only one of these may appear, or none if the
 327      * constructor has default (package) access.
 328      *
 329      * @return a string describing this {@code Constructor}
 330      * @jls 8.8.3 Constructor Modifiers
 331      * @jls 8.9.2 Enum Body Declarations
 332      */
 333     public String toString() {
 334         return sharedToString(Modifier.constructorModifiers(),
 335                               false,
 336                               parameterTypes,
 337                               exceptionTypes);
 338     }
 339 
 340     @Override
 341     void specificToStringHeader(StringBuilder sb) {
 342         sb.append(getDeclaringClass().getTypeName());
 343     }
 344 
 345     /**
 346      * Returns a string describing this {@code Constructor},
 347      * including type parameters.  The string is formatted as the
 348      * constructor access modifiers, if any, followed by an
 349      * angle-bracketed comma separated list of the constructor's type
 350      * parameters, if any, followed by the fully-qualified name of the
 351      * declaring class, followed by a parenthesized, comma-separated
 352      * list of the constructor's generic formal parameter types.
 353      *
 354      * If this constructor was declared to take a variable number of
 355      * arguments, instead of denoting the last parameter as
 356      * "<code><i>Type</i>[]</code>", it is denoted as
 357      * "<code><i>Type</i>...</code>".
 358      *
 359      * A space is used to separate access modifiers from one another
 360      * and from the type parameters or return type.  If there are no
 361      * type parameters, the type parameter list is elided; if the type
 362      * parameter list is present, a space separates the list from the
 363      * class name.  If the constructor is declared to throw
 364      * exceptions, the parameter list is followed by a space, followed
 365      * by the word "{@code throws}" followed by a
 366      * comma-separated list of the thrown exception types.
 367      *
 368      * <p>The only possible modifiers for constructors are the access
 369      * modifiers {@code public}, {@code protected} or
 370      * {@code private}.  Only one of these may appear, or none if the
 371      * constructor has default (package) access.
 372      *
 373      * @return a string describing this {@code Constructor},
 374      * include type parameters
 375      *
 376      * @since 1.5
 377      * @jls 8.8.3 Constructor Modifiers
 378      * @jls 8.9.2 Enum Body Declarations
 379      */
 380     @Override
 381     public String toGenericString() {
 382         return sharedToGenericString(Modifier.constructorModifiers(), false);
 383     }
 384 
 385     @Override
 386     void specificToGenericStringHeader(StringBuilder sb) {
 387         specificToStringHeader(sb);
 388     }
 389 
 390     /**
 391      * Uses the constructor represented by this {@code Constructor} object to
 392      * create and initialize a new instance of the constructor's
 393      * declaring class, with the specified initialization parameters.
 394      * Individual parameters are automatically unwrapped to match
 395      * primitive formal parameters, and both primitive and reference
 396      * parameters are subject to method invocation conversions as necessary.
 397      *
 398      * <p>If the number of formal parameters required by the underlying constructor
 399      * is 0, the supplied {@code initargs} array may be of length 0 or null.
 400      *
 401      * <p>If the constructor's declaring class is an inner class in a
 402      * non-static context, the first argument to the constructor needs
 403      * to be the enclosing instance; see section 15.9.3 of
 404      * <cite>The Java&trade; Language Specification</cite>.
 405      *
 406      * <p>If the required access and argument checks succeed and the
 407      * instantiation will proceed, the constructor's declaring class
 408      * is initialized if it has not already been initialized.
 409      *
 410      * <p>If the constructor completes normally, returns the newly
 411      * created and initialized instance.
 412      *
 413      * @param initargs array of objects to be passed as arguments to
 414      * the constructor call; values of primitive types are wrapped in
 415      * a wrapper object of the appropriate type (e.g. a {@code float}
 416      * in a {@link java.lang.Float Float})
 417      *
 418      * @return a new object created by calling the constructor
 419      * this object represents
 420      *
 421      * @exception IllegalAccessException    if this {@code Constructor} object
 422      *              is enforcing Java language access control and the underlying
 423      *              constructor is inaccessible.
 424      * @exception IllegalArgumentException  if the number of actual
 425      *              and formal parameters differ; if an unwrapping
 426      *              conversion for primitive arguments fails; or if,
 427      *              after possible unwrapping, a parameter value
 428      *              cannot be converted to the corresponding formal
 429      *              parameter type by a method invocation conversion; if
 430      *              this constructor pertains to an enum type.
 431      * @exception InstantiationException    if the class that declares the
 432      *              underlying constructor represents an abstract class.
 433      * @exception InvocationTargetException if the underlying constructor
 434      *              throws an exception.
 435      * @exception ExceptionInInitializerError if the initialization provoked
 436      *              by this method fails.
 437      */
 438     @CallerSensitive
 439     @ForceInline // to ensure Reflection.getCallerClass optimization
 440     public T newInstance(Object ... initargs)
 441         throws InstantiationException, IllegalAccessException,
 442                IllegalArgumentException, InvocationTargetException
 443     {
 444         if (!override) {
 445             Class<?> caller = Reflection.getCallerClass();
 446             checkAccess(caller, clazz, clazz, modifiers);
 447         }
 448         if ((clazz.getModifiers() & Modifier.ENUM) != 0)
 449             throw new IllegalArgumentException("Cannot reflectively create enum objects");
 450         ConstructorAccessor ca = constructorAccessor;   // read volatile
 451         if (ca == null) {
 452             ca = acquireConstructorAccessor();
 453         }
 454         @SuppressWarnings("unchecked")
 455         T inst = (T) ca.newInstance(initargs);
 456         return inst;
 457     }
 458 
 459     /**
 460      * {@inheritDoc}
 461      * @since 1.5
 462      */
 463     @Override
 464     public boolean isVarArgs() {
 465         return super.isVarArgs();
 466     }
 467 
 468     /**
 469      * {@inheritDoc}
 470      * @jls 13.1 The Form of a Binary
 471      * @since 1.5
 472      */
 473     @Override
 474     public boolean isSynthetic() {
 475         return super.isSynthetic();
 476     }
 477 
 478     // NOTE that there is no synchronization used here. It is correct
 479     // (though not efficient) to generate more than one
 480     // ConstructorAccessor for a given Constructor. However, avoiding
 481     // synchronization will probably make the implementation more
 482     // scalable.
 483     private ConstructorAccessor acquireConstructorAccessor() {
 484         // First check to see if one has been created yet, and take it
 485         // if so.
 486         ConstructorAccessor tmp = null;
 487         if (root != null) tmp = root.getConstructorAccessor();
 488         if (tmp != null) {
 489             constructorAccessor = tmp;
 490         } else {
 491             // Otherwise fabricate one and propagate it up to the root
 492             tmp = reflectionFactory.newConstructorAccessor(this);
 493             setConstructorAccessor(tmp);
 494         }
 495 
 496         return tmp;
 497     }
 498 
 499     // Returns ConstructorAccessor for this Constructor object, not
 500     // looking up the chain to the root
 501     ConstructorAccessor getConstructorAccessor() {
 502         return constructorAccessor;
 503     }
 504 
 505     // Sets the ConstructorAccessor for this Constructor object and
 506     // (recursively) its root
 507     void setConstructorAccessor(ConstructorAccessor accessor) {
 508         constructorAccessor = accessor;
 509         // Propagate up
 510         if (root != null) {
 511             root.setConstructorAccessor(accessor);
 512         }
 513     }
 514 
 515     int getSlot() {
 516         return slot;
 517     }
 518 
 519     String getSignature() {
 520         return signature;
 521     }
 522 
 523     byte[] getRawAnnotations() {
 524         return annotations;
 525     }
 526 
 527     byte[] getRawParameterAnnotations() {
 528         return parameterAnnotations;
 529     }
 530 
 531 
 532     /**
 533      * {@inheritDoc}
 534      * @throws NullPointerException  {@inheritDoc}
 535      * @since 1.5
 536      */
 537     public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
 538         return super.getAnnotation(annotationClass);
 539     }
 540 
 541     /**
 542      * {@inheritDoc}
 543      * @since 1.5
 544      */
 545     public Annotation[] getDeclaredAnnotations()  {
 546         return super.getDeclaredAnnotations();
 547     }
 548 
 549     /**
 550      * {@inheritDoc}
 551      * @since 1.5
 552      */
 553     @Override
 554     public Annotation[][] getParameterAnnotations() {
 555         return sharedGetParameterAnnotations(parameterTypes, parameterAnnotations);
 556     }
 557 
 558     @Override
 559     void handleParameterNumberMismatch(int resultLength, int numParameters) {
 560         Class<?> declaringClass = getDeclaringClass();
 561         if (declaringClass.isEnum() ||
 562             declaringClass.isAnonymousClass() ||
 563             declaringClass.isLocalClass() )
 564             return ; // Can't do reliable parameter counting
 565         else {
 566             if (!declaringClass.isMemberClass() || // top-level
 567                 // Check for the enclosing instance parameter for
 568                 // non-static member classes
 569                 (declaringClass.isMemberClass() &&
 570                  ((declaringClass.getModifiers() & Modifier.STATIC) == 0)  &&
 571                  resultLength + 1 != numParameters) ) {
 572                 throw new AnnotationFormatError(
 573                           "Parameter annotations don't match number of parameters");
 574             }
 575         }
 576     }
 577 
 578     /**
 579      * {@inheritDoc}
 580      * @since 1.8
 581      */
 582     @Override
 583     public AnnotatedType getAnnotatedReturnType() {
 584         return getAnnotatedReturnType0(getDeclaringClass());
 585     }
 586 
 587     /**
 588      * {@inheritDoc}
 589      * @since 1.8
 590      */
 591     @Override
 592     public AnnotatedType getAnnotatedReceiverType() {
 593         Class<?> thisDeclClass = getDeclaringClass();
 594         Class<?> enclosingClass = thisDeclClass.getEnclosingClass();
 595 
 596         if (enclosingClass == null) {
 597             // A Constructor for a top-level class
 598             return null;
 599         }
 600 
 601         Class<?> outerDeclaringClass = thisDeclClass.getDeclaringClass();
 602         if (outerDeclaringClass == null) {
 603             // A constructor for a local or anonymous class
 604             return null;
 605         }
 606 
 607         // Either static nested or inner class
 608         if (Modifier.isStatic(thisDeclClass.getModifiers())) {
 609             // static nested
 610             return null;
 611         }
 612 
 613         // A Constructor for an inner class
 614         return TypeAnnotationParser.buildAnnotatedType(getTypeAnnotationBytes0(),
 615                 SharedSecrets.getJavaLangAccess().
 616                     getConstantPool(thisDeclClass),
 617                 this,
 618                 thisDeclClass,
 619                 enclosingClass,
 620                 TypeAnnotation.TypeAnnotationTarget.METHOD_RECEIVER);
 621     }
 622 }