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      * Returns the {@code Class} object representing the class that
 204      * declares the constructor represented by this object.
 205      */
 206     @Override
 207     public Class<T> getDeclaringClass() {
 208         return clazz;
 209     }
 210 
 211     /**
 212      * Returns the name of this constructor, as a string.  This is
 213      * the binary name of the constructor's declaring class.
 214      */
 215     @Override
 216     public String getName() {
 217         return getDeclaringClass().getName();
 218     }
 219 
 220     /**
 221      * {@inheritDoc}
 222      */
 223     @Override
 224     public int getModifiers() {
 225         return modifiers;
 226     }
 227 
 228     /**
 229      * {@inheritDoc}
 230      * @throws GenericSignatureFormatError {@inheritDoc}
 231      * @since 1.5
 232      */
 233     @Override
 234     @SuppressWarnings({"rawtypes", "unchecked"})
 235     public TypeVariable<Constructor<T>>[] getTypeParameters() {
 236       if (getSignature() != null) {
 237         return (TypeVariable<Constructor<T>>[])getGenericInfo().getTypeParameters();
 238       } else
 239           return (TypeVariable<Constructor<T>>[])new TypeVariable[0];
 240     }
 241 
 242 
 243     /**
 244      * {@inheritDoc}
 245      */
 246     @Override
 247     public Class<?>[] getParameterTypes() {
 248         return parameterTypes.clone();
 249     }
 250 
 251     /**
 252      * {@inheritDoc}
 253      * @since 1.8
 254      */
 255     public int getParameterCount() { return parameterTypes.length; }
 256 
 257     /**
 258      * {@inheritDoc}
 259      * @throws GenericSignatureFormatError {@inheritDoc}
 260      * @throws TypeNotPresentException {@inheritDoc}
 261      * @throws MalformedParameterizedTypeException {@inheritDoc}
 262      * @since 1.5
 263      */
 264     @Override
 265     public Type[] getGenericParameterTypes() {
 266         return super.getGenericParameterTypes();
 267     }
 268 
 269     /**
 270      * {@inheritDoc}
 271      */
 272     @Override
 273     public Class<?>[] getExceptionTypes() {
 274         return exceptionTypes.clone();
 275     }
 276 
 277 
 278     /**
 279      * {@inheritDoc}
 280      * @throws GenericSignatureFormatError {@inheritDoc}
 281      * @throws TypeNotPresentException {@inheritDoc}
 282      * @throws MalformedParameterizedTypeException {@inheritDoc}
 283      * @since 1.5
 284      */
 285     @Override
 286     public Type[] getGenericExceptionTypes() {
 287         return super.getGenericExceptionTypes();
 288     }
 289 
 290     /**
 291      * Compares this {@code Constructor} against the specified object.
 292      * Returns true if the objects are the same.  Two {@code Constructor} objects are
 293      * the same if they were declared by the same class and have the
 294      * same formal parameter types.
 295      */
 296     public boolean equals(Object obj) {
 297         if (obj != null && obj instanceof Constructor) {
 298             Constructor<?> other = (Constructor<?>)obj;
 299             if (getDeclaringClass() == other.getDeclaringClass()) {
 300                 return equalParamTypes(parameterTypes, other.parameterTypes);
 301             }
 302         }
 303         return false;
 304     }
 305 
 306     /**
 307      * Returns a hashcode for this {@code Constructor}. The hashcode is
 308      * the same as the hashcode for the underlying constructor's
 309      * declaring class name.
 310      */
 311     public int hashCode() {
 312         return getDeclaringClass().getName().hashCode();
 313     }
 314 
 315     /**
 316      * Returns a string describing this {@code Constructor}.  The string is
 317      * formatted as the constructor access modifiers, if any,
 318      * followed by the fully-qualified name of the declaring class,
 319      * followed by a parenthesized, comma-separated list of the
 320      * constructor's formal parameter types.  For example:
 321      * <pre>{@code
 322      *    public java.util.Hashtable(int,float)
 323      * }</pre>
 324      *
 325      * <p>If the constructor is declared to throw exceptions, the
 326      * parameter list is followed by a space, followed by the word
 327      * "{@code throws}" followed by a comma-separated list of the
 328      * thrown exception types.
 329      *
 330      * <p>The only possible modifiers for constructors are the access
 331      * modifiers {@code public}, {@code protected} or
 332      * {@code private}.  Only one of these may appear, or none if the
 333      * constructor has default (package) access.
 334      *
 335      * @return a string describing this {@code Constructor}
 336      * @jls 8.8.3 Constructor Modifiers
 337      * @jls 8.9.2 Enum Body Declarations
 338      */
 339     public String toString() {
 340         return sharedToString(Modifier.constructorModifiers(),
 341                               false,
 342                               parameterTypes,
 343                               exceptionTypes);
 344     }
 345 
 346     @Override
 347     void specificToStringHeader(StringBuilder sb) {
 348         sb.append(getDeclaringClass().getTypeName());
 349     }
 350 
 351     /**
 352      * Returns a string describing this {@code Constructor},
 353      * including type parameters.  The string is formatted as the
 354      * constructor access modifiers, if any, followed by an
 355      * angle-bracketed comma separated list of the constructor's type
 356      * parameters, if any, followed by the fully-qualified name of the
 357      * declaring class, followed by a parenthesized, comma-separated
 358      * list of the constructor's generic formal parameter types.
 359      *
 360      * If this constructor was declared to take a variable number of
 361      * arguments, instead of denoting the last parameter as
 362      * "<code><i>Type</i>[]</code>", it is denoted as
 363      * "<code><i>Type</i>...</code>".
 364      *
 365      * A space is used to separate access modifiers from one another
 366      * and from the type parameters or class name.  If there are no
 367      * type parameters, the type parameter list is elided; if the type
 368      * parameter list is present, a space separates the list from the
 369      * class name.  If the constructor is declared to throw
 370      * exceptions, the parameter list is followed by a space, followed
 371      * by the word "{@code throws}" followed by a
 372      * comma-separated list of the generic thrown exception types.
 373      *
 374      * <p>The only possible modifiers for constructors are the access
 375      * modifiers {@code public}, {@code protected} or
 376      * {@code private}.  Only one of these may appear, or none if the
 377      * constructor has default (package) access.
 378      *
 379      * @return a string describing this {@code Constructor},
 380      * include type parameters
 381      *
 382      * @since 1.5
 383      * @jls 8.8.3 Constructor Modifiers
 384      * @jls 8.9.2 Enum Body Declarations
 385      */
 386     @Override
 387     public String toGenericString() {
 388         return sharedToGenericString(Modifier.constructorModifiers(), false);
 389     }
 390 
 391     @Override
 392     void specificToGenericStringHeader(StringBuilder sb) {
 393         specificToStringHeader(sb);
 394     }
 395 
 396     /**
 397      * Uses the constructor represented by this {@code Constructor} object to
 398      * create and initialize a new instance of the constructor's
 399      * declaring class, with the specified initialization parameters.
 400      * Individual parameters are automatically unwrapped to match
 401      * primitive formal parameters, and both primitive and reference
 402      * parameters are subject to method invocation conversions as necessary.
 403      *
 404      * <p>If the number of formal parameters required by the underlying constructor
 405      * is 0, the supplied {@code initargs} array may be of length 0 or null.
 406      *
 407      * <p>If the constructor's declaring class is an inner class in a
 408      * non-static context, the first argument to the constructor needs
 409      * to be the enclosing instance; see section 15.9.3 of
 410      * <cite>The Java&trade; Language Specification</cite>.
 411      *
 412      * <p>If the required access and argument checks succeed and the
 413      * instantiation will proceed, the constructor's declaring class
 414      * is initialized if it has not already been initialized.
 415      *
 416      * <p>If the constructor completes normally, returns the newly
 417      * created and initialized instance.
 418      *
 419      * @param initargs array of objects to be passed as arguments to
 420      * the constructor call; values of primitive types are wrapped in
 421      * a wrapper object of the appropriate type (e.g. a {@code float}
 422      * in a {@link java.lang.Float Float})
 423      *
 424      * @return a new object created by calling the constructor
 425      * this object represents
 426      *
 427      * @exception IllegalAccessException    if this {@code Constructor} object
 428      *              is enforcing Java language access control and the underlying
 429      *              constructor is inaccessible.
 430      * @exception IllegalArgumentException  if the number of actual
 431      *              and formal parameters differ; if an unwrapping
 432      *              conversion for primitive arguments fails; or if,
 433      *              after possible unwrapping, a parameter value
 434      *              cannot be converted to the corresponding formal
 435      *              parameter type by a method invocation conversion; if
 436      *              this constructor pertains to an enum type.
 437      * @exception InstantiationException    if the class that declares the
 438      *              underlying constructor represents an abstract class.
 439      * @exception InvocationTargetException if the underlying constructor
 440      *              throws an exception.
 441      * @exception ExceptionInInitializerError if the initialization provoked
 442      *              by this method fails.
 443      */
 444     @CallerSensitive
 445     @ForceInline // to ensure Reflection.getCallerClass optimization
 446     public T newInstance(Object ... initargs)
 447         throws InstantiationException, IllegalAccessException,
 448                IllegalArgumentException, InvocationTargetException
 449     {
 450         if (!override) {
 451             Class<?> caller = Reflection.getCallerClass();
 452             checkAccess(caller, clazz, clazz, modifiers);
 453         }
 454         if ((clazz.getModifiers() & Modifier.ENUM) != 0)
 455             throw new IllegalArgumentException("Cannot reflectively create enum objects");
 456         ConstructorAccessor ca = constructorAccessor;   // read volatile
 457         if (ca == null) {
 458             ca = acquireConstructorAccessor();
 459         }
 460         @SuppressWarnings("unchecked")
 461         T inst = (T) ca.newInstance(initargs);
 462         return inst;
 463     }
 464 
 465     /**
 466      * {@inheritDoc}
 467      * @since 1.5
 468      */
 469     @Override
 470     public boolean isVarArgs() {
 471         return super.isVarArgs();
 472     }
 473 
 474     /**
 475      * {@inheritDoc}
 476      * @jls 13.1 The Form of a Binary
 477      * @since 1.5
 478      */
 479     @Override
 480     public boolean isSynthetic() {
 481         return super.isSynthetic();
 482     }
 483 
 484     // NOTE that there is no synchronization used here. It is correct
 485     // (though not efficient) to generate more than one
 486     // ConstructorAccessor for a given Constructor. However, avoiding
 487     // synchronization will probably make the implementation more
 488     // scalable.
 489     private ConstructorAccessor acquireConstructorAccessor() {
 490         // First check to see if one has been created yet, and take it
 491         // if so.
 492         ConstructorAccessor tmp = null;
 493         if (root != null) tmp = root.getConstructorAccessor();
 494         if (tmp != null) {
 495             constructorAccessor = tmp;
 496         } else {
 497             // Otherwise fabricate one and propagate it up to the root
 498             tmp = reflectionFactory.newConstructorAccessor(this);
 499             setConstructorAccessor(tmp);
 500         }
 501 
 502         return tmp;
 503     }
 504 
 505     // Returns ConstructorAccessor for this Constructor object, not
 506     // looking up the chain to the root
 507     ConstructorAccessor getConstructorAccessor() {
 508         return constructorAccessor;
 509     }
 510 
 511     // Sets the ConstructorAccessor for this Constructor object and
 512     // (recursively) its root
 513     void setConstructorAccessor(ConstructorAccessor accessor) {
 514         constructorAccessor = accessor;
 515         // Propagate up
 516         if (root != null) {
 517             root.setConstructorAccessor(accessor);
 518         }
 519     }
 520 
 521     int getSlot() {
 522         return slot;
 523     }
 524 
 525     String getSignature() {
 526         return signature;
 527     }
 528 
 529     byte[] getRawAnnotations() {
 530         return annotations;
 531     }
 532 
 533     byte[] getRawParameterAnnotations() {
 534         return parameterAnnotations;
 535     }
 536 
 537 
 538     /**
 539      * {@inheritDoc}
 540      * @throws NullPointerException  {@inheritDoc}
 541      * @since 1.5
 542      */
 543     public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
 544         return super.getAnnotation(annotationClass);
 545     }
 546 
 547     /**
 548      * {@inheritDoc}
 549      * @since 1.5
 550      */
 551     public Annotation[] getDeclaredAnnotations()  {
 552         return super.getDeclaredAnnotations();
 553     }
 554 
 555     /**
 556      * {@inheritDoc}
 557      * @since 1.5
 558      */
 559     @Override
 560     public Annotation[][] getParameterAnnotations() {
 561         return sharedGetParameterAnnotations(parameterTypes, parameterAnnotations);
 562     }
 563 
 564     @Override
 565     void handleParameterNumberMismatch(int resultLength, int numParameters) {
 566         Class<?> declaringClass = getDeclaringClass();
 567         if (declaringClass.isEnum() ||
 568             declaringClass.isAnonymousClass() ||
 569             declaringClass.isLocalClass() )
 570             return ; // Can't do reliable parameter counting
 571         else {
 572             if (!declaringClass.isMemberClass() || // top-level
 573                 // Check for the enclosing instance parameter for
 574                 // non-static member classes
 575                 (declaringClass.isMemberClass() &&
 576                  ((declaringClass.getModifiers() & Modifier.STATIC) == 0)  &&
 577                  resultLength + 1 != numParameters) ) {
 578                 throw new AnnotationFormatError(
 579                           "Parameter annotations don't match number of parameters");
 580             }
 581         }
 582     }
 583 
 584     /**
 585      * {@inheritDoc}
 586      * @since 1.8
 587      */
 588     @Override
 589     public AnnotatedType getAnnotatedReturnType() {
 590         return getAnnotatedReturnType0(getDeclaringClass());
 591     }
 592 
 593     /**
 594      * {@inheritDoc}
 595      * @since 1.8
 596      */
 597     @Override
 598     public AnnotatedType getAnnotatedReceiverType() {
 599         Class<?> thisDeclClass = getDeclaringClass();
 600         Class<?> enclosingClass = thisDeclClass.getEnclosingClass();
 601 
 602         if (enclosingClass == null) {
 603             // A Constructor for a top-level class
 604             return null;
 605         }
 606 
 607         Class<?> outerDeclaringClass = thisDeclClass.getDeclaringClass();
 608         if (outerDeclaringClass == null) {
 609             // A constructor for a local or anonymous class
 610             return null;
 611         }
 612 
 613         // Either static nested or inner class
 614         if (Modifier.isStatic(thisDeclClass.getModifiers())) {
 615             // static nested
 616             return null;
 617         }
 618 
 619         // A Constructor for an inner class
 620         return TypeAnnotationParser.buildAnnotatedType(getTypeAnnotationBytes0(),
 621                 SharedSecrets.getJavaLangAccess().
 622                     getConstantPool(thisDeclClass),
 623                 this,
 624                 thisDeclClass,
 625                 enclosingClass,
 626                 TypeAnnotation.TypeAnnotationTarget.METHOD_RECEIVER);
 627     }
 628 }