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