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