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