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.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     @Override
 158     byte[] getTypeAnnotationBytes() {
 159         return typeAnnotations;
 160     }
 161 
 162     /**
 163      * {@inheritDoc}
 164      */
 165     @Override
 166     public Class<T> getDeclaringClass() {
 167         return clazz;
 168     }
 169 
 170     /**
 171      * Returns the name of this constructor, as a string.  This is
 172      * the binary name of the constructor's declaring class.
 173      */
 174     @Override
 175     public String getName() {
 176         return getDeclaringClass().getName();
 177     }
 178 
 179     /**
 180      * {@inheritDoc}
 181      */
 182     @Override
 183     public int getModifiers() {
 184         return modifiers;
 185     }
 186 
 187     /**
 188      * {@inheritDoc}
 189      * @throws GenericSignatureFormatError {@inheritDoc}
 190      * @since 1.5
 191      */
 192     @Override
 193     @SuppressWarnings({"rawtypes", "unchecked"})
 194     public TypeVariable<Constructor<T>>[] getTypeParameters() {
 195       if (getSignature() != null) {
 196         return (TypeVariable<Constructor<T>>[])getGenericInfo().getTypeParameters();
 197       } else
 198           return (TypeVariable<Constructor<T>>[])new TypeVariable[0];
 199     }
 200 
 201 
 202     /**
 203      * {@inheritDoc}
 204      */
 205     @Override
 206     public Class<?>[] getParameterTypes() {
 207         return parameterTypes.clone();
 208     }
 209 
 210     /**
 211      * {@inheritDoc}
 212      */
 213     public int getParameterCount() { return parameterTypes.length; }
 214 
 215     /**
 216      * {@inheritDoc}
 217      * @throws GenericSignatureFormatError {@inheritDoc}
 218      * @throws TypeNotPresentException {@inheritDoc}
 219      * @throws MalformedParameterizedTypeException {@inheritDoc}
 220      * @since 1.5
 221      */
 222     @Override
 223     public Type[] getGenericParameterTypes() {
 224         return super.getGenericParameterTypes();
 225     }
 226 
 227     /**
 228      * {@inheritDoc}
 229      */
 230     @Override
 231     public Class<?>[] getExceptionTypes() {
 232         return exceptionTypes.clone();
 233     }
 234 
 235 
 236     /**
 237      * {@inheritDoc}
 238      * @throws GenericSignatureFormatError {@inheritDoc}
 239      * @throws TypeNotPresentException {@inheritDoc}
 240      * @throws MalformedParameterizedTypeException {@inheritDoc}
 241      * @since 1.5
 242      */
 243     @Override
 244     public Type[] getGenericExceptionTypes() {
 245         return super.getGenericExceptionTypes();
 246     }
 247 
 248     /**
 249      * Compares this {@code Constructor} against the specified object.
 250      * Returns true if the objects are the same.  Two {@code Constructor} objects are
 251      * the same if they were declared by the same class and have the
 252      * same formal parameter types.
 253      */
 254     public boolean equals(Object obj) {
 255         if (obj != null && obj instanceof Constructor) {
 256             Constructor<?> other = (Constructor<?>)obj;
 257             if (getDeclaringClass() == other.getDeclaringClass()) {
 258                 return equalParamTypes(parameterTypes, other.parameterTypes);
 259             }
 260         }
 261         return false;
 262     }
 263 
 264     /**
 265      * Returns a hashcode for this {@code Constructor}. The hashcode is
 266      * the same as the hashcode for the underlying constructor's
 267      * declaring class name.
 268      */
 269     public int hashCode() {
 270         return getDeclaringClass().getName().hashCode();
 271     }
 272 
 273     /**
 274      * Returns a string describing this {@code Constructor}.  The string is
 275      * formatted as the constructor access modifiers, if any,
 276      * followed by the fully-qualified name of the declaring class,
 277      * followed by a parenthesized, comma-separated list of the
 278      * constructor's formal parameter types.  For example:
 279      * <pre>
 280      *    public java.util.Hashtable(int,float)
 281      * </pre>
 282      *
 283      * <p>The only possible modifiers for constructors are the access
 284      * modifiers {@code public}, {@code protected} or
 285      * {@code private}.  Only one of these may appear, or none if the
 286      * constructor has default (package) access.
 287      */
 288     public String toString() {
 289         return sharedToString(Modifier.constructorModifiers(),
 290                               parameterTypes,
 291                               exceptionTypes);
 292     }
 293 
 294     @Override
 295     void specificToStringHeader(StringBuilder sb) {
 296         sb.append(Field.getTypeName(getDeclaringClass()));
 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      */
 332     @Override
 333     public String toGenericString() {
 334         return sharedToGenericString(Modifier.constructorModifiers());
 335     }
 336 
 337     @Override
 338     void specificToGenericStringHeader(StringBuilder sb) {
 339         specificToStringHeader(sb);
 340     }
 341 
 342     /**
 343      * Uses the constructor represented by this {@code Constructor} object to
 344      * create and initialize a new instance of the constructor's
 345      * declaring class, with the specified initialization parameters.
 346      * Individual parameters are automatically unwrapped to match
 347      * primitive formal parameters, and both primitive and reference
 348      * parameters are subject to method invocation conversions as necessary.
 349      *
 350      * <p>If the number of formal parameters required by the underlying constructor
 351      * is 0, the supplied {@code initargs} array may be of length 0 or null.
 352      *
 353      * <p>If the constructor's declaring class is an inner class in a
 354      * non-static context, the first argument to the constructor needs
 355      * to be the enclosing instance; see section 15.9.3 of
 356      * <cite>The Java&trade; Language Specification</cite>.
 357      *
 358      * <p>If the required access and argument checks succeed and the
 359      * instantiation will proceed, the constructor's declaring class
 360      * is initialized if it has not already been initialized.
 361      *
 362      * <p>If the constructor completes normally, returns the newly
 363      * created and initialized instance.
 364      *
 365      * @param initargs array of objects to be passed as arguments to
 366      * the constructor call; values of primitive types are wrapped in
 367      * a wrapper object of the appropriate type (e.g. a {@code float}
 368      * in a {@link java.lang.Float Float})
 369      *
 370      * @return a new object created by calling the constructor
 371      * this object represents
 372      *
 373      * @exception IllegalAccessException    if this {@code Constructor} object
 374      *              is enforcing Java language access control and the underlying
 375      *              constructor is inaccessible.
 376      * @exception IllegalArgumentException  if the number of actual
 377      *              and formal parameters differ; if an unwrapping
 378      *              conversion for primitive arguments fails; or if,
 379      *              after possible unwrapping, a parameter value
 380      *              cannot be converted to the corresponding formal
 381      *              parameter type by a method invocation conversion; if
 382      *              this constructor pertains to an enum type.
 383      * @exception InstantiationException    if the class that declares the
 384      *              underlying constructor represents an abstract class.
 385      * @exception InvocationTargetException if the underlying constructor
 386      *              throws an exception.
 387      * @exception ExceptionInInitializerError if the initialization provoked
 388      *              by this method fails.
 389      */
 390     public T newInstance(Object ... initargs)
 391         throws InstantiationException, IllegalAccessException,
 392                IllegalArgumentException, InvocationTargetException
 393     {
 394         if (!override) {
 395             if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
 396                 Class<?> caller = Reflection.getCallerClass(2);
 397 
 398                 checkAccess(caller, clazz, null, modifiers);
 399             }
 400         }
 401         if ((clazz.getModifiers() & Modifier.ENUM) != 0)
 402             throw new IllegalArgumentException("Cannot reflectively create enum objects");
 403         ConstructorAccessor ca = constructorAccessor;   // read volatile
 404         if (ca == null) {
 405             ca = acquireConstructorAccessor();
 406         }
 407         @SuppressWarnings("unchecked")
 408         T inst = (T) ca.newInstance(initargs);
 409         return inst;
 410     }
 411 
 412     /**
 413      * {@inheritDoc}
 414      * @since 1.5
 415      */
 416     @Override
 417     public boolean isVarArgs() {
 418         return super.isVarArgs();
 419     }
 420 
 421     /**
 422      * {@inheritDoc}
 423      * @jls 13.1 The Form of a Binary
 424      * @since 1.5
 425      */
 426     @Override
 427     public boolean isSynthetic() {
 428         return super.isSynthetic();
 429     }
 430 
 431     // NOTE that there is no synchronization used here. It is correct
 432     // (though not efficient) to generate more than one
 433     // ConstructorAccessor for a given Constructor. However, avoiding
 434     // synchronization will probably make the implementation more
 435     // scalable.
 436     private ConstructorAccessor acquireConstructorAccessor() {
 437         // First check to see if one has been created yet, and take it
 438         // if so.
 439         ConstructorAccessor tmp = null;
 440         if (root != null) tmp = root.getConstructorAccessor();
 441         if (tmp != null) {
 442             constructorAccessor = tmp;
 443         } else {
 444             // Otherwise fabricate one and propagate it up to the root
 445             tmp = reflectionFactory.newConstructorAccessor(this);
 446             setConstructorAccessor(tmp);
 447         }
 448 
 449         return tmp;
 450     }
 451 
 452     // Returns ConstructorAccessor for this Constructor object, not
 453     // looking up the chain to the root
 454     ConstructorAccessor getConstructorAccessor() {
 455         return constructorAccessor;
 456     }
 457 
 458     // Sets the ConstructorAccessor for this Constructor object and
 459     // (recursively) its root
 460     void setConstructorAccessor(ConstructorAccessor accessor) {
 461         constructorAccessor = accessor;
 462         // Propagate up
 463         if (root != null) {
 464             root.setConstructorAccessor(accessor);
 465         }
 466     }
 467 
 468     int getSlot() {
 469         return slot;
 470     }
 471 
 472     String getSignature() {
 473         return signature;
 474     }
 475 
 476     byte[] getRawAnnotations() {
 477         return annotations;
 478     }
 479 
 480     byte[] getRawParameterAnnotations() {
 481         return parameterAnnotations;
 482     }
 483 
 484 
 485     /**
 486      * {@inheritDoc}
 487      * @throws NullPointerException  {@inheritDoc}
 488      * @since 1.5
 489      */
 490     public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
 491         return super.getAnnotation(annotationClass);
 492     }
 493 
 494     /**
 495      * {@inheritDoc}
 496      * @since 1.5
 497      */
 498     public Annotation[] getDeclaredAnnotations()  {
 499         return super.getDeclaredAnnotations();
 500     }
 501 
 502     /**
 503      * {@inheritDoc}
 504      * @since 1.5
 505      */
 506     @Override
 507     public Annotation[][] getParameterAnnotations() {
 508         return sharedGetParameterAnnotations(parameterTypes, parameterAnnotations);
 509     }
 510 
 511     @Override
 512     void handleParameterNumberMismatch(int resultLength, int numParameters) {
 513         Class<?> declaringClass = getDeclaringClass();
 514         if (declaringClass.isEnum() ||
 515             declaringClass.isAnonymousClass() ||
 516             declaringClass.isLocalClass() )
 517             return ; // Can't do reliable parameter counting
 518         else {
 519             if (!declaringClass.isMemberClass() || // top-level
 520                 // Check for the enclosing instance parameter for
 521                 // non-static member classes
 522                 (declaringClass.isMemberClass() &&
 523                  ((declaringClass.getModifiers() & Modifier.STATIC) == 0)  &&
 524                  resultLength + 1 != numParameters) ) {
 525                 throw new AnnotationFormatError(
 526                           "Parameter annotations don't match number of parameters");
 527             }
 528         }
 529     }
 530 
 531     /**
 532      * {@inheritDoc}
 533      * @since 1.8
 534      */
 535     @Override
 536     public AnnotatedType getAnnotatedReturnType() {
 537         return getAnnotatedReturnType0(getDeclaringClass());
 538     }
 539 }