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