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