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