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