47 * {@code IllegalArgumentException} if a narrowing conversion would occur.
48 *
49 * @param <T> the class in which the constructor is declared
50 *
51 * @see Member
52 * @see java.lang.Class
53 * @see java.lang.Class#getConstructors()
54 * @see java.lang.Class#getConstructor(Class[])
55 * @see java.lang.Class#getDeclaredConstructors()
56 *
57 * @author Kenneth Russell
58 * @author Nakul Saraiya
59 */
60 public final
61 class Constructor<T> extends AccessibleObject implements
62 GenericDeclaration,
63 Member {
64
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 // For non-public members or members in package-private classes,
78 // it is necessary to perform somewhat expensive security checks.
79 // If the security check succeeds for a given class, it will
80 // always succeed (it is not affected by the granting or revoking
81 // of permissions); we speed up the check in the common case by
82 // remembering the last Class for which the check succeeded.
83 private volatile Class securityCheckCache;
84
85 // Generics infrastructure
86 // Accessor for factory
87 private GenericsFactory getFactory() {
88 // create scope and factory
89 return CoreReflectionFactory.make(this, ConstructorScope.make(this));
90 }
91
92 // Accessor for generic info repository
93 private ConstructorRepository getGenericInfo() {
94 // lazily initialize repository if necessary
95 if (genericInfo == null) {
96 // create and cache generic info repository
97 genericInfo =
98 ConstructorRepository.make(getSignature(),
99 getFactory());
100 }
101 return genericInfo; //return cached repository
102 }
103
104 private volatile ConstructorAccessor constructorAccessor;
105 // For sharing of ConstructorAccessors. This branching structure
106 // is currently only two levels deep (i.e., one root Constructor
107 // and potentially many Constructor objects pointing to it.)
108 private Constructor<T> root;
109
110 /**
111 * Package-private constructor used by ReflectAccess to enable
112 * instantiation of these objects in Java code from the java.lang
113 * package via sun.reflect.LangReflectAccess.
114 */
115 Constructor(Class<T> declaringClass,
116 Class[] parameterTypes,
117 Class[] checkedExceptions,
118 int modifiers,
119 int slot,
120 String signature,
121 byte[] annotations,
122 byte[] parameterAnnotations)
123 {
124 this.clazz = declaringClass;
125 this.parameterTypes = parameterTypes;
126 this.exceptionTypes = checkedExceptions;
127 this.modifiers = modifiers;
128 this.slot = slot;
129 this.signature = signature;
130 this.annotations = annotations;
131 this.parameterAnnotations = parameterAnnotations;
132 }
133
134 /**
135 * Package-private routine (exposed to java.lang.Class via
136 * ReflectAccess) which returns a copy of this Constructor. The copy's
137 * "root" field points to this Constructor.
290 * parameterized type that cannot be instantiated for any reason
291 * @since 1.5
292 */
293 public Type[] getGenericExceptionTypes() {
294 Type[] result;
295 if (getSignature() != null &&
296 ( (result = getGenericInfo().getExceptionTypes()).length > 0 ))
297 return result;
298 else
299 return getExceptionTypes();
300 }
301
302 /**
303 * Compares this {@code Constructor} against the specified object.
304 * Returns true if the objects are the same. Two {@code Constructor} objects are
305 * the same if they were declared by the same class and have the
306 * same formal parameter types.
307 */
308 public boolean equals(Object obj) {
309 if (obj != null && obj instanceof Constructor) {
310 Constructor other = (Constructor)obj;
311 if (getDeclaringClass() == other.getDeclaringClass()) {
312 /* Avoid unnecessary cloning */
313 Class[] params1 = parameterTypes;
314 Class[] params2 = other.parameterTypes;
315 if (params1.length == params2.length) {
316 for (int i = 0; i < params1.length; i++) {
317 if (params1[i] != params2[i])
318 return false;
319 }
320 return true;
321 }
322 }
323 }
324 return false;
325 }
326
327 /**
328 * Returns a hashcode for this {@code Constructor}. The hashcode is
329 * the same as the hashcode for the underlying constructor's
330 * declaring class name.
331 */
332 public int hashCode() {
333 return getDeclaringClass().getName().hashCode();
334 }
340 * followed by a parenthesized, comma-separated list of the
341 * constructor's formal parameter types. For example:
342 * <pre>
343 * public java.util.Hashtable(int,float)
344 * </pre>
345 *
346 * <p>The only possible modifiers for constructors are the access
347 * modifiers {@code public}, {@code protected} or
348 * {@code private}. Only one of these may appear, or none if the
349 * constructor has default (package) access.
350 */
351 public String toString() {
352 try {
353 StringBuffer sb = new StringBuffer();
354 int mod = getModifiers() & Modifier.constructorModifiers();
355 if (mod != 0) {
356 sb.append(Modifier.toString(mod) + " ");
357 }
358 sb.append(Field.getTypeName(getDeclaringClass()));
359 sb.append("(");
360 Class[] params = parameterTypes; // avoid clone
361 for (int j = 0; j < params.length; j++) {
362 sb.append(Field.getTypeName(params[j]));
363 if (j < (params.length - 1))
364 sb.append(",");
365 }
366 sb.append(")");
367 Class[] exceptions = exceptionTypes; // avoid clone
368 if (exceptions.length > 0) {
369 sb.append(" throws ");
370 for (int k = 0; k < exceptions.length; k++) {
371 sb.append(exceptions[k].getName());
372 if (k < (exceptions.length - 1))
373 sb.append(",");
374 }
375 }
376 return sb.toString();
377 } catch (Exception e) {
378 return "<" + e + ">";
379 }
380 }
381
382 /**
383 * Returns a string describing this {@code Constructor},
384 * including type parameters. The string is formatted as the
385 * constructor access modifiers, if any, followed by an
386 * angle-bracketed comma separated list of the constructor's type
387 * parameters, if any, followed by the fully-qualified name of the
435 }
436 sb.append(Field.getTypeName(getDeclaringClass()));
437 sb.append("(");
438 Type[] params = getGenericParameterTypes();
439 for (int j = 0; j < params.length; j++) {
440 String param = (params[j] instanceof Class<?>)?
441 Field.getTypeName((Class<?>)params[j]):
442 (params[j].toString());
443 if (isVarArgs() && (j == params.length - 1)) // replace T[] with T...
444 param = param.replaceFirst("\\[\\]$", "...");
445 sb.append(param);
446 if (j < (params.length - 1))
447 sb.append(",");
448 }
449 sb.append(")");
450 Type[] exceptions = getGenericExceptionTypes();
451 if (exceptions.length > 0) {
452 sb.append(" throws ");
453 for (int k = 0; k < exceptions.length; k++) {
454 sb.append((exceptions[k] instanceof Class)?
455 ((Class)exceptions[k]).getName():
456 exceptions[k].toString());
457 if (k < (exceptions.length - 1))
458 sb.append(",");
459 }
460 }
461 return sb.toString();
462 } catch (Exception e) {
463 return "<" + e + ">";
464 }
465 }
466
467 /**
468 * Uses the constructor represented by this {@code Constructor} object to
469 * create and initialize a new instance of the constructor's
470 * declaring class, with the specified initialization parameters.
471 * Individual parameters are automatically unwrapped to match
472 * primitive formal parameters, and both primitive and reference
473 * parameters are subject to method invocation conversions as necessary.
474 *
475 * <p>If the number of formal parameters required by the underlying constructor
501 * @exception IllegalArgumentException if the number of actual
502 * and formal parameters differ; if an unwrapping
503 * conversion for primitive arguments fails; or if,
504 * after possible unwrapping, a parameter value
505 * cannot be converted to the corresponding formal
506 * parameter type by a method invocation conversion; if
507 * this constructor pertains to an enum type.
508 * @exception InstantiationException if the class that declares the
509 * underlying constructor represents an abstract class.
510 * @exception InvocationTargetException if the underlying constructor
511 * throws an exception.
512 * @exception ExceptionInInitializerError if the initialization provoked
513 * by this method fails.
514 */
515 public T newInstance(Object ... initargs)
516 throws InstantiationException, IllegalAccessException,
517 IllegalArgumentException, InvocationTargetException
518 {
519 if (!override) {
520 if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
521 Class caller = Reflection.getCallerClass(2);
522 if (securityCheckCache != caller) {
523 Reflection.ensureMemberAccess(caller, clazz, null, modifiers);
524 securityCheckCache = caller;
525 }
526 }
527 }
528 if ((clazz.getModifiers() & Modifier.ENUM) != 0)
529 throw new IllegalArgumentException("Cannot reflectively create enum objects");
530 if (constructorAccessor == null) acquireConstructorAccessor();
531 return (T) constructorAccessor.newInstance(initargs);
532 }
533
534 /**
535 * Returns {@code true} if this constructor was declared to take
536 * a variable number of arguments; returns {@code false}
537 * otherwise.
538 *
539 * @return {@code true} if an only if this constructor was declared to
540 * take a variable number of arguments.
541 * @since 1.5
608 }
609
610 /**
611 * @throws NullPointerException {@inheritDoc}
612 * @since 1.5
613 */
614 public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
615 if (annotationClass == null)
616 throw new NullPointerException();
617
618 return (T) declaredAnnotations().get(annotationClass);
619 }
620
621 /**
622 * @since 1.5
623 */
624 public Annotation[] getDeclaredAnnotations() {
625 return AnnotationParser.toArray(declaredAnnotations());
626 }
627
628 private transient Map<Class, Annotation> declaredAnnotations;
629
630 private synchronized Map<Class, Annotation> declaredAnnotations() {
631 if (declaredAnnotations == null) {
632 declaredAnnotations = AnnotationParser.parseAnnotations(
633 annotations, sun.misc.SharedSecrets.getJavaLangAccess().
634 getConstantPool(getDeclaringClass()),
635 getDeclaringClass());
636 }
637 return declaredAnnotations;
638 }
639
640 /**
641 * Returns an array of arrays that represent the annotations on the formal
642 * parameters, in declaration order, of the method represented by
643 * this {@code Constructor} object. (Returns an array of length zero if the
644 * underlying method is parameterless. If the method has one or more
645 * parameters, a nested array of length zero is returned for each parameter
646 * with no annotations.) The annotation objects contained in the returned
647 * arrays are serializable. The caller of this method is free to modify
648 * the returned arrays; it will have no effect on the arrays returned to
649 * other callers.
650 *
|
47 * {@code IllegalArgumentException} if a narrowing conversion would occur.
48 *
49 * @param <T> the class in which the constructor is declared
50 *
51 * @see Member
52 * @see java.lang.Class
53 * @see java.lang.Class#getConstructors()
54 * @see java.lang.Class#getConstructor(Class[])
55 * @see java.lang.Class#getDeclaredConstructors()
56 *
57 * @author Kenneth Russell
58 * @author Nakul Saraiya
59 */
60 public final
61 class Constructor<T> extends AccessibleObject implements
62 GenericDeclaration,
63 Member {
64
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 // For non-public members or members in package-private classes,
78 // it is necessary to perform somewhat expensive security checks.
79 // If the security check succeeds for a given class, it will
80 // always succeed (it is not affected by the granting or revoking
81 // of permissions); we speed up the check in the common case by
82 // remembering the last Class for which the check succeeded.
83 private volatile Class<?> securityCheckCache;
84
85 // Generics infrastructure
86 // Accessor for factory
87 private GenericsFactory getFactory() {
88 // create scope and factory
89 return CoreReflectionFactory.make(this, ConstructorScope.make(this));
90 }
91
92 // Accessor for generic info repository
93 private ConstructorRepository getGenericInfo() {
94 // lazily initialize repository if necessary
95 if (genericInfo == null) {
96 // create and cache generic info repository
97 genericInfo =
98 ConstructorRepository.make(getSignature(),
99 getFactory());
100 }
101 return genericInfo; //return cached repository
102 }
103
104 private volatile ConstructorAccessor constructorAccessor;
105 // For sharing of ConstructorAccessors. This branching structure
106 // is currently only two levels deep (i.e., one root Constructor
107 // and potentially many Constructor objects pointing to it.)
108 private Constructor<T> root;
109
110 /**
111 * Package-private constructor used by ReflectAccess to enable
112 * instantiation of these objects in Java code from the java.lang
113 * package via sun.reflect.LangReflectAccess.
114 */
115 Constructor(Class<T> declaringClass,
116 Class<?>[] parameterTypes,
117 Class<?>[] checkedExceptions,
118 int modifiers,
119 int slot,
120 String signature,
121 byte[] annotations,
122 byte[] parameterAnnotations)
123 {
124 this.clazz = declaringClass;
125 this.parameterTypes = parameterTypes;
126 this.exceptionTypes = checkedExceptions;
127 this.modifiers = modifiers;
128 this.slot = slot;
129 this.signature = signature;
130 this.annotations = annotations;
131 this.parameterAnnotations = parameterAnnotations;
132 }
133
134 /**
135 * Package-private routine (exposed to java.lang.Class via
136 * ReflectAccess) which returns a copy of this Constructor. The copy's
137 * "root" field points to this Constructor.
290 * parameterized type that cannot be instantiated for any reason
291 * @since 1.5
292 */
293 public Type[] getGenericExceptionTypes() {
294 Type[] result;
295 if (getSignature() != null &&
296 ( (result = getGenericInfo().getExceptionTypes()).length > 0 ))
297 return result;
298 else
299 return getExceptionTypes();
300 }
301
302 /**
303 * Compares this {@code Constructor} against the specified object.
304 * Returns true if the objects are the same. Two {@code Constructor} objects are
305 * the same if they were declared by the same class and have the
306 * same formal parameter types.
307 */
308 public boolean equals(Object obj) {
309 if (obj != null && obj instanceof Constructor) {
310 Constructor<?> other = (Constructor<?>)obj;
311 if (getDeclaringClass() == other.getDeclaringClass()) {
312 /* Avoid unnecessary cloning */
313 Class<?>[] params1 = parameterTypes;
314 Class<?>[] params2 = other.parameterTypes;
315 if (params1.length == params2.length) {
316 for (int i = 0; i < params1.length; i++) {
317 if (params1[i] != params2[i])
318 return false;
319 }
320 return true;
321 }
322 }
323 }
324 return false;
325 }
326
327 /**
328 * Returns a hashcode for this {@code Constructor}. The hashcode is
329 * the same as the hashcode for the underlying constructor's
330 * declaring class name.
331 */
332 public int hashCode() {
333 return getDeclaringClass().getName().hashCode();
334 }
340 * followed by a parenthesized, comma-separated list of the
341 * constructor's formal parameter types. For example:
342 * <pre>
343 * public java.util.Hashtable(int,float)
344 * </pre>
345 *
346 * <p>The only possible modifiers for constructors are the access
347 * modifiers {@code public}, {@code protected} or
348 * {@code private}. Only one of these may appear, or none if the
349 * constructor has default (package) access.
350 */
351 public String toString() {
352 try {
353 StringBuffer sb = new StringBuffer();
354 int mod = getModifiers() & Modifier.constructorModifiers();
355 if (mod != 0) {
356 sb.append(Modifier.toString(mod) + " ");
357 }
358 sb.append(Field.getTypeName(getDeclaringClass()));
359 sb.append("(");
360 Class<?>[] params = parameterTypes; // avoid clone
361 for (int j = 0; j < params.length; j++) {
362 sb.append(Field.getTypeName(params[j]));
363 if (j < (params.length - 1))
364 sb.append(",");
365 }
366 sb.append(")");
367 Class<?>[] exceptions = exceptionTypes; // avoid clone
368 if (exceptions.length > 0) {
369 sb.append(" throws ");
370 for (int k = 0; k < exceptions.length; k++) {
371 sb.append(exceptions[k].getName());
372 if (k < (exceptions.length - 1))
373 sb.append(",");
374 }
375 }
376 return sb.toString();
377 } catch (Exception e) {
378 return "<" + e + ">";
379 }
380 }
381
382 /**
383 * Returns a string describing this {@code Constructor},
384 * including type parameters. The string is formatted as the
385 * constructor access modifiers, if any, followed by an
386 * angle-bracketed comma separated list of the constructor's type
387 * parameters, if any, followed by the fully-qualified name of the
435 }
436 sb.append(Field.getTypeName(getDeclaringClass()));
437 sb.append("(");
438 Type[] params = getGenericParameterTypes();
439 for (int j = 0; j < params.length; j++) {
440 String param = (params[j] instanceof Class<?>)?
441 Field.getTypeName((Class<?>)params[j]):
442 (params[j].toString());
443 if (isVarArgs() && (j == params.length - 1)) // replace T[] with T...
444 param = param.replaceFirst("\\[\\]$", "...");
445 sb.append(param);
446 if (j < (params.length - 1))
447 sb.append(",");
448 }
449 sb.append(")");
450 Type[] exceptions = getGenericExceptionTypes();
451 if (exceptions.length > 0) {
452 sb.append(" throws ");
453 for (int k = 0; k < exceptions.length; k++) {
454 sb.append((exceptions[k] instanceof Class)?
455 ((Class<?>)exceptions[k]).getName():
456 exceptions[k].toString());
457 if (k < (exceptions.length - 1))
458 sb.append(",");
459 }
460 }
461 return sb.toString();
462 } catch (Exception e) {
463 return "<" + e + ">";
464 }
465 }
466
467 /**
468 * Uses the constructor represented by this {@code Constructor} object to
469 * create and initialize a new instance of the constructor's
470 * declaring class, with the specified initialization parameters.
471 * Individual parameters are automatically unwrapped to match
472 * primitive formal parameters, and both primitive and reference
473 * parameters are subject to method invocation conversions as necessary.
474 *
475 * <p>If the number of formal parameters required by the underlying constructor
501 * @exception IllegalArgumentException if the number of actual
502 * and formal parameters differ; if an unwrapping
503 * conversion for primitive arguments fails; or if,
504 * after possible unwrapping, a parameter value
505 * cannot be converted to the corresponding formal
506 * parameter type by a method invocation conversion; if
507 * this constructor pertains to an enum type.
508 * @exception InstantiationException if the class that declares the
509 * underlying constructor represents an abstract class.
510 * @exception InvocationTargetException if the underlying constructor
511 * throws an exception.
512 * @exception ExceptionInInitializerError if the initialization provoked
513 * by this method fails.
514 */
515 public T newInstance(Object ... initargs)
516 throws InstantiationException, IllegalAccessException,
517 IllegalArgumentException, InvocationTargetException
518 {
519 if (!override) {
520 if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
521 Class<?> caller = Reflection.getCallerClass(2);
522 if (securityCheckCache != caller) {
523 Reflection.ensureMemberAccess(caller, clazz, null, modifiers);
524 securityCheckCache = caller;
525 }
526 }
527 }
528 if ((clazz.getModifiers() & Modifier.ENUM) != 0)
529 throw new IllegalArgumentException("Cannot reflectively create enum objects");
530 if (constructorAccessor == null) acquireConstructorAccessor();
531 return (T) constructorAccessor.newInstance(initargs);
532 }
533
534 /**
535 * Returns {@code true} if this constructor was declared to take
536 * a variable number of arguments; returns {@code false}
537 * otherwise.
538 *
539 * @return {@code true} if an only if this constructor was declared to
540 * take a variable number of arguments.
541 * @since 1.5
608 }
609
610 /**
611 * @throws NullPointerException {@inheritDoc}
612 * @since 1.5
613 */
614 public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
615 if (annotationClass == null)
616 throw new NullPointerException();
617
618 return (T) declaredAnnotations().get(annotationClass);
619 }
620
621 /**
622 * @since 1.5
623 */
624 public Annotation[] getDeclaredAnnotations() {
625 return AnnotationParser.toArray(declaredAnnotations());
626 }
627
628 private transient Map<Class<? extends Annotation>, Annotation> declaredAnnotations;
629
630 private synchronized Map<Class<? extends Annotation>, Annotation> declaredAnnotations() {
631 if (declaredAnnotations == null) {
632 declaredAnnotations = AnnotationParser.parseAnnotations(
633 annotations, sun.misc.SharedSecrets.getJavaLangAccess().
634 getConstantPool(getDeclaringClass()),
635 getDeclaringClass());
636 }
637 return declaredAnnotations;
638 }
639
640 /**
641 * Returns an array of arrays that represent the annotations on the formal
642 * parameters, in declaration order, of the method represented by
643 * this {@code Constructor} object. (Returns an array of length zero if the
644 * underlying method is parameterless. If the method has one or more
645 * parameters, a nested array of length zero is returned for each parameter
646 * with no annotations.) The annotation objects contained in the returned
647 * arrays are serializable. The caller of this method is free to modify
648 * the returned arrays; it will have no effect on the arrays returned to
649 * other callers.
650 *
|