001 /*
002 * Copyright 1996-2006 Sun Microsystems, Inc. All Rights Reserved.
003 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
004 *
005 * This code is free software; you can redistribute it and/or modify it
006 * under the terms of the GNU General Public License version 2 only, as
007 * published by the Free Software Foundation. Sun designates this
008 * particular file as subject to the "Classpath" exception as provided
009 * by Sun in the LICENSE file that accompanied this code.
010 *
011 * This code is distributed in the hope that it will be useful, but WITHOUT
012 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
013 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
014 * version 2 for more details (a copy is included in the LICENSE file that
015 * accompanied this code).
016 *
017 * You should have received a copy of the GNU General Public License version
018 * 2 along with this work; if not, write to the Free Software Foundation,
019 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
020 *
021 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
022 * CA 95054 USA or visit www.sun.com if you need additional information or
023 * have any questions.
024 */
025
026 package java.lang.reflect;
027
028 import sun.reflect.ConstructorAccessor;
029 import sun.reflect.Reflection;
030 import sun.reflect.generics.repository.ConstructorRepository;
031 import sun.reflect.generics.factory.CoreReflectionFactory;
032 import sun.reflect.generics.factory.GenericsFactory;
033 import sun.reflect.generics.scope.ConstructorScope;
034 import java.lang.annotation.Annotation;
035 import java.util.Map;
036 import sun.reflect.annotation.AnnotationParser;
037 import java.lang.annotation.AnnotationFormatError;
038 import java.lang.reflect.Modifier;
039
040 /**
041 * {@code Constructor} provides information about, and access to, a single
042 * constructor for a class.
043 *
044 * <p>{@code Constructor} permits widening conversions to occur when matching the
045 * actual parameters to newInstance() with the underlying
046 * constructor's formal parameters, but throws an
047 * {@code IllegalArgumentException} if a narrowing conversion would occur.
048 *
049 * @param <T> the class in which the constructor is declared
050 *
051 * @see Member
052 * @see java.lang.Class
053 * @see java.lang.Class#getConstructors()
054 * @see java.lang.Class#getConstructor(Class[])
055 * @see java.lang.Class#getDeclaredConstructors()
056 *
057 * @author Kenneth Russell
058 * @author Nakul Saraiya
059 */
060 public final class Constructor<T> extends AccessibleObject implements
061 GenericDeclaration, Member {
062
063 private Class<T> clazz;
064 private int slot;
065 private Class[] parameterTypes;
066 private Class[] exceptionTypes;
067 private int modifiers;
068 // Generics and annotations support
069 private transient String signature;
070 // generic info repository; lazily initialized
071 private transient ConstructorRepository genericInfo;
072 private byte[] annotations;
073 private byte[] parameterAnnotations;
074
075 // For non-public members or members in package-private classes,
076 // it is necessary to perform somewhat expensive security checks.
077 // If the security check succeeds for a given class, it will
078 // always succeed (it is not affected by the granting or revoking
079 // of permissions); we speed up the check in the common case by
080 // remembering the last Class for which the check succeeded.
081 private volatile Class securityCheckCache;
082
083 // Modifiers that can be applied to a constructor in source code
084 private static final int LANGUAGE_MODIFIERS = Modifier.PUBLIC
085 | Modifier.PROTECTED | Modifier.PRIVATE;
086
087 // Generics infrastructure
088 // Accessor for factory
089 private GenericsFactory getFactory() {
090 // create scope and factory
091 return CoreReflectionFactory.make(this , ConstructorScope
092 .make(this ));
093 }
094
095 // Accessor for generic info repository
096 private ConstructorRepository getGenericInfo() {
097 // lazily initialize repository if necessary
098 if (genericInfo == null) {
099 // create and cache generic info repository
100 genericInfo = ConstructorRepository.make(getSignature(),
101 getFactory());
102 }
103 return genericInfo; //return cached repository
104 }
105
106 private volatile ConstructorAccessor constructorAccessor;
107 // For sharing of ConstructorAccessors. This branching structure
108 // is currently only two levels deep (i.e., one root Constructor
109 // and potentially many Constructor objects pointing to it.)
110 private Constructor<T> root;
111
112 /**
113 * Package-private constructor used by ReflectAccess to enable
114 * instantiation of these objects in Java code from the java.lang
115 * package via sun.reflect.LangReflectAccess.
116 */
117 Constructor(Class<T> declaringClass, Class[] parameterTypes,
118 Class[] checkedExceptions, int modifiers, int slot,
119 String signature, byte[] annotations,
120 byte[] parameterAnnotations) {
121 this .clazz = declaringClass;
122 this .parameterTypes = parameterTypes;
123 this .exceptionTypes = checkedExceptions;
124 this .modifiers = modifiers;
125 this .slot = slot;
126 this .signature = signature;
127 this .annotations = annotations;
128 this .parameterAnnotations = parameterAnnotations;
129 }
130
131 /**
132 * Package-private routine (exposed to java.lang.Class via
133 * ReflectAccess) which returns a copy of this Constructor. The copy's
134 * "root" field points to this Constructor.
135 */
136 Constructor<T> copy() {
137 // This routine enables sharing of ConstructorAccessor objects
138 // among Constructor objects which refer to the same underlying
139 // method in the VM. (All of this contortion is only necessary
140 // because of the "accessibility" bit in AccessibleObject,
141 // which implicitly requires that new java.lang.reflect
142 // objects be fabricated for each reflective call on Class
143 // objects.)
144 Constructor<T> res = new Constructor<T>(clazz, parameterTypes,
145 exceptionTypes, modifiers, slot, signature,
146 annotations, parameterAnnotations);
147 res.root = this ;
148 // Might as well eagerly propagate this if already present
149 res.constructorAccessor = constructorAccessor;
150 return res;
151 }
152
153 /**
154 * Returns the {@code Class} object representing the class that declares
155 * the constructor represented by this {@code Constructor} object.
156 */
157 public Class<T> getDeclaringClass() {
158 return clazz;
159 }
160
161 /**
162 * Returns the name of this constructor, as a string. This is
163 * always the same as the simple name of the constructor's declaring
164 * class.
165 */
166 public String getName() {
167 return getDeclaringClass().getName();
168 }
169
170 /**
171 * Returns the Java language modifiers for the constructor
172 * represented by this {@code Constructor} object, as an integer. The
173 * {@code Modifier} class should be used to decode the modifiers.
174 *
175 * @see Modifier
176 */
177 public int getModifiers() {
178 return modifiers;
179 }
180
181 /**
182 * Returns an array of {@code TypeVariable} objects that represent the
183 * type variables declared by the generic declaration represented by this
184 * {@code GenericDeclaration} object, in declaration order. Returns an
185 * array of length 0 if the underlying generic declaration declares no type
186 * variables.
187 *
188 * @return an array of {@code TypeVariable} objects that represent
189 * the type variables declared by this generic declaration
190 * @throws GenericSignatureFormatError if the generic
191 * signature of this generic declaration does not conform to
192 * the format specified in the Java Virtual Machine Specification,
193 * 3rd edition
194 * @since 1.5
195 */
196 public TypeVariable<Constructor<T>>[] getTypeParameters() {
197 if (getSignature() != null) {
198 return (TypeVariable<Constructor<T>>[]) getGenericInfo()
199 .getTypeParameters();
200 } else
201 return (TypeVariable<Constructor<T>>[]) new TypeVariable[0];
202 }
203
204 /**
205 * Returns an array of {@code Class} objects that represent the formal
206 * parameter types, in declaration order, of the constructor
207 * represented by this {@code Constructor} object. Returns an array of
208 * length 0 if the underlying constructor takes no parameters.
209 *
210 * @return the parameter types for the constructor this object
211 * represents
212 */
213 public Class<?>[] getParameterTypes() {
214 return (Class<?>[]) parameterTypes.clone();
215 }
216
217 /**
218 * Returns an array of {@code Type} objects that represent the formal
219 * parameter types, in declaration order, of the method represented by
220 * this {@code Constructor} object. Returns an array of length 0 if the
221 * underlying method takes no parameters.
222 *
223 * <p>If a formal parameter type is a parameterized type,
224 * the {@code Type} object returned for it must accurately reflect
225 * the actual type parameters used in the source code.
226 *
227 * <p>If a formal parameter type is a type variable or a parameterized
228 * type, it is created. Otherwise, it is resolved.
229 *
230 * @return an array of {@code Type}s that represent the formal
231 * parameter types of the underlying method, in declaration order
232 * @throws GenericSignatureFormatError
233 * if the generic method signature does not conform to the format
234 * specified in the Java Virtual Machine Specification, 3rd edition
235 * @throws TypeNotPresentException if any of the parameter
236 * types of the underlying method refers to a non-existent type
237 * declaration
238 * @throws MalformedParameterizedTypeException if any of
239 * the underlying method's parameter types refer to a parameterized
240 * type that cannot be instantiated for any reason
241 * @since 1.5
242 */
243 public Type[] getGenericParameterTypes() {
244 if (getSignature() != null)
245 return getGenericInfo().getParameterTypes();
246 else
247 return getParameterTypes();
248 }
249
250 /**
251 * Returns an array of {@code Class} objects that represent the types
252 * of exceptions declared to be thrown by the underlying constructor
253 * represented by this {@code Constructor} object. Returns an array of
254 * length 0 if the constructor declares no exceptions in its {@code throws} clause.
255 *
256 * @return the exception types declared as being thrown by the
257 * constructor this object represents
258 */
259 public Class<?>[] getExceptionTypes() {
260 return (Class<?>[]) exceptionTypes.clone();
261 }
262
263 /**
264 * Returns an array of {@code Type} objects that represent the
265 * exceptions declared to be thrown by this {@code Constructor} object.
266 * Returns an array of length 0 if the underlying method declares
267 * no exceptions in its {@code throws} clause.
268 *
269 * <p>If an exception type is a parameterized type, the {@code Type}
270 * object returned for it must accurately reflect the actual type
271 * parameters used in the source code.
272 *
273 * <p>If an exception type is a type variable or a parameterized
274 * type, it is created. Otherwise, it is resolved.
275 *
276 * @return an array of Types that represent the exception types
277 * thrown by the underlying method
278 * @throws GenericSignatureFormatError
279 * if the generic method signature does not conform to the format
280 * specified in the Java Virtual Machine Specification, 3rd edition
281 * @throws TypeNotPresentException if the underlying method's
282 * {@code throws} clause refers to a non-existent type declaration
283 * @throws MalformedParameterizedTypeException if
284 * the underlying method's {@code throws} clause refers to a
285 * parameterized type that cannot be instantiated for any reason
286 * @since 1.5
287 */
288 public Type[] getGenericExceptionTypes() {
289 Type[] result;
290 if (getSignature() != null
291 && ((result = getGenericInfo().getExceptionTypes()).length > 0))
292 return result;
293 else
294 return getExceptionTypes();
295 }
296
297 /**
298 * Compares this {@code Constructor} against the specified object.
299 * Returns true if the objects are the same. Two {@code Constructor} objects are
300 * the same if they were declared by the same class and have the
301 * same formal parameter types.
302 */
303 public boolean equals(Object obj) {
304 if (obj != null && obj instanceof Constructor) {
305 Constructor other = (Constructor) obj;
306 if (getDeclaringClass() == other.getDeclaringClass()) {
307 /* Avoid unnecessary cloning */
308 Class[] params1 = parameterTypes;
309 Class[] params2 = other.parameterTypes;
310 if (params1.length == params2.length) {
311 for (int i = 0; i < params1.length; i++) {
312 if (params1[i] != params2[i])
313 return false;
314 }
315 return true;
316 }
317 }
318 }
319 return false;
320 }
321
322 /**
323 * Returns a hashcode for this {@code Constructor}. The hashcode is
324 * the same as the hashcode for the underlying constructor's
325 * declaring class name.
326 */
327 public int hashCode() {
328 return getDeclaringClass().getName().hashCode();
329 }
330
331 /**
332 * Returns a string describing this {@code Constructor}. The string is
333 * formatted as the constructor access modifiers, if any,
334 * followed by the fully-qualified name of the declaring class,
335 * followed by a parenthesized, comma-separated list of the
336 * constructor's formal parameter types. For example:
337 * <pre>
338 * public java.util.Hashtable(int,float)
339 * </pre>
340 *
341 * <p>The only possible modifiers for constructors are the access
342 * modifiers {@code public}, {@code protected} or
343 * {@code private}. Only one of these may appear, or none if the
344 * constructor has default (package) access.
345 */
346 public String toString() {
347 try {
348 StringBuffer sb = new StringBuffer();
349 int mod = getModifiers() & LANGUAGE_MODIFIERS;
350 if (mod != 0) {
351 sb.append(Modifier.toString(mod) + " ");
352 }
353 sb.append(Field.getTypeName(getDeclaringClass()));
354 sb.append("(");
355 Class[] params = parameterTypes; // avoid clone
356 for (int j = 0; j < params.length; j++) {
357 sb.append(Field.getTypeName(params[j]));
358 if (j < (params.length - 1))
359 sb.append(",");
360 }
361 sb.append(")");
362 Class[] exceptions = exceptionTypes; // avoid clone
363 if (exceptions.length > 0) {
364 sb.append(" throws ");
365 for (int k = 0; k < exceptions.length; k++) {
366 sb.append(exceptions[k].getName());
367 if (k < (exceptions.length - 1))
368 sb.append(",");
369 }
370 }
371 return sb.toString();
372 } catch (Exception e) {
373 return "<" + e + ">";
374 }
375 }
376
377 /**
378 * Returns a string describing this {@code Constructor},
379 * including type parameters. The string is formatted as the
380 * constructor access modifiers, if any, followed by an
381 * angle-bracketed comma separated list of the constructor's type
382 * parameters, if any, followed by the fully-qualified name of the
383 * declaring class, followed by a parenthesized, comma-separated
384 * list of the constructor's generic formal parameter types.
385 *
386 * If this constructor was declared to take a variable number of
387 * arguments, instead of denoting the last parameter as
388 * "<tt><i>Type</i>[]</tt>", it is denoted as
389 * "<tt><i>Type</i>...</tt>".
390 *
391 * A space is used to separate access modifiers from one another
392 * and from the type parameters or return type. If there are no
393 * type parameters, the type parameter list is elided; if the type
394 * parameter list is present, a space separates the list from the
395 * class name. If the constructor is declared to throw
396 * exceptions, the parameter list is followed by a space, followed
397 * by the word "{@code throws}" followed by a
398 * comma-separated list of the thrown exception types.
399 *
400 * <p>The only possible modifiers for constructors are the access
401 * modifiers {@code public}, {@code protected} or
402 * {@code private}. Only one of these may appear, or none if the
403 * constructor has default (package) access.
404 *
405 * @return a string describing this {@code Constructor},
406 * include type parameters
407 *
408 * @since 1.5
409 */
410 public String toGenericString() {
411 try {
412 StringBuilder sb = new StringBuilder();
413 int mod = getModifiers() & LANGUAGE_MODIFIERS;
414 if (mod != 0) {
415 sb.append(Modifier.toString(mod) + " ");
416 }
417 TypeVariable<?>[] typeparms = getTypeParameters();
418 if (typeparms.length > 0) {
419 boolean first = true;
420 sb.append("<");
421 for (TypeVariable<?> typeparm : typeparms) {
422 if (!first)
423 sb.append(",");
424 // Class objects can't occur here; no need to test
425 // and call Class.getName().
426 sb.append(typeparm.toString());
427 first = false;
428 }
429 sb.append("> ");
430 }
431 sb.append(Field.getTypeName(getDeclaringClass()));
432 sb.append("(");
433 Type[] params = getGenericParameterTypes();
434 for (int j = 0; j < params.length; j++) {
435 String param = (params[j] instanceof Class<?>) ? Field
436 .getTypeName((Class<?>) params[j]) : (params[j]
437 .toString());
438 if (isVarArgs() && (j == params.length - 1)) // replace T[] with T...
439 param = param.replaceFirst("\\[\\]$", "...");
440 sb.append(param);
441 if (j < (params.length - 1))
442 sb.append(",");
443 }
444 sb.append(")");
445 Type[] exceptions = getGenericExceptionTypes();
446 if (exceptions.length > 0) {
447 sb.append(" throws ");
448 for (int k = 0; k < exceptions.length; k++) {
449 sb
450 .append((exceptions[k] instanceof Class) ? ((Class) exceptions[k])
451 .getName()
452 : exceptions[k].toString());
453 if (k < (exceptions.length - 1))
454 sb.append(",");
455 }
456 }
457 return sb.toString();
458 } catch (Exception e) {
459 return "<" + e + ">";
460 }
461 }
462
463 /**
464 * Uses the constructor represented by this {@code Constructor} object to
465 * create and initialize a new instance of the constructor's
466 * declaring class, with the specified initialization parameters.
467 * Individual parameters are automatically unwrapped to match
468 * primitive formal parameters, and both primitive and reference
469 * parameters are subject to method invocation conversions as necessary.
470 *
471 * <p>If the number of formal parameters required by the underlying constructor
472 * is 0, the supplied {@code initargs} array may be of length 0 or null.
473 *
474 * <p>If the constructor's declaring class is an inner class in a
475 * non-static context, the first argument to the constructor needs
476 * to be the enclosing instance; see <i>The Java Language
477 * Specification</i>, section 15.9.3.
478 *
479 * <p>If the required access and argument checks succeed and the
480 * instantiation will proceed, the constructor's declaring class
481 * is initialized if it has not already been initialized.
482 *
483 * <p>If the constructor completes normally, returns the newly
484 * created and initialized instance.
485 *
486 * @param initargs array of objects to be passed as arguments to
487 * the constructor call; values of primitive types are wrapped in
488 * a wrapper object of the appropriate type (e.g. a {@code float}
489 * in a {@link java.lang.Float Float})
490 *
491 * @return a new object created by calling the constructor
492 * this object represents
493 *
494 * @exception IllegalAccessException if this {@code Constructor} object
495 * enforces Java language access control and the underlying
496 * constructor is inaccessible.
497 * @exception IllegalArgumentException if the number of actual
498 * and formal parameters differ; if an unwrapping
499 * conversion for primitive arguments fails; or if,
500 * after possible unwrapping, a parameter value
501 * cannot be converted to the corresponding formal
502 * parameter type by a method invocation conversion; if
503 * this constructor pertains to an enum type.
504 * @exception InstantiationException if the class that declares the
505 * underlying constructor represents an abstract class.
506 * @exception InvocationTargetException if the underlying constructor
507 * throws an exception.
508 * @exception ExceptionInInitializerError if the initialization provoked
509 * by this method fails.
510 */
511 public T newInstance(Object... initargs)
512 throws InstantiationException, IllegalAccessException,
513 IllegalArgumentException, InvocationTargetException {
514 if (!override) {
515 if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
516 Class caller = Reflection.getCallerClass(2);
517 if (securityCheckCache != caller) {
518 Reflection.ensureMemberAccess(caller, clazz, null,
519 modifiers);
520 securityCheckCache = caller;
521 }
522 }
523 }
524 if ((clazz.getModifiers() & Modifier.ENUM) != 0)
525 throw new IllegalArgumentException(
526 "Cannot reflectively create enum objects");
527 if (constructorAccessor == null)
528 acquireConstructorAccessor();
529 return (T) constructorAccessor.newInstance(initargs);
530 }
531
532 /**
533 * Returns {@code true} if this constructor was declared to take
534 * a variable number of arguments; returns {@code false}
535 * otherwise.
536 *
537 * @return {@code true} if an only if this constructor was declared to
538 * take a variable number of arguments.
539 * @since 1.5
540 */
541 public boolean isVarArgs() {
542 return (getModifiers() & Modifier.VARARGS) != 0;
543 }
544
545 /**
546 * Returns {@code true} if this constructor is a synthetic
547 * constructor; returns {@code false} otherwise.
548 *
549 * @return true if and only if this constructor is a synthetic
550 * constructor as defined by the Java Language Specification.
551 * @since 1.5
552 */
553 public boolean isSynthetic() {
554 return Modifier.isSynthetic(getModifiers());
555 }
556
557 // NOTE that there is no synchronization used here. It is correct
558 // (though not efficient) to generate more than one
559 // ConstructorAccessor for a given Constructor. However, avoiding
560 // synchronization will probably make the implementation more
561 // scalable.
562 private void acquireConstructorAccessor() {
563 // First check to see if one has been created yet, and take it
564 // if so.
565 ConstructorAccessor tmp = null;
566 if (root != null)
567 tmp = root.getConstructorAccessor();
568 if (tmp != null) {
569 constructorAccessor = tmp;
570 return;
571 }
572 // Otherwise fabricate one and propagate it up to the root
573 tmp = reflectionFactory.newConstructorAccessor(this );
574 setConstructorAccessor(tmp);
575 }
576
577 // Returns ConstructorAccessor for this Constructor object, not
578 // looking up the chain to the root
579 ConstructorAccessor getConstructorAccessor() {
580 return constructorAccessor;
581 }
582
583 // Sets the ConstructorAccessor for this Constructor object and
584 // (recursively) its root
585 void setConstructorAccessor(ConstructorAccessor accessor) {
586 constructorAccessor = accessor;
587 // Propagate up
588 if (root != null) {
589 root.setConstructorAccessor(accessor);
590 }
591 }
592
593 int getSlot() {
594 return slot;
595 }
596
597 String getSignature() {
598 return signature;
599 }
600
601 byte[] getRawAnnotations() {
602 return annotations;
603 }
604
605 byte[] getRawParameterAnnotations() {
606 return parameterAnnotations;
607 }
608
609 /**
610 * @throws NullPointerException {@inheritDoc}
611 * @since 1.5
612 */
613 public <T extends Annotation> T getAnnotation(
614 Class<T> annotationClass) {
615 if (annotationClass == null)
616 throw new NullPointerException();
617
618 return (T) declaredAnnotations().get(annotationClass);
619 }
620
621 private static final Annotation[] EMPTY_ANNOTATION_ARRAY = new Annotation[0];
622
623 /**
624 * @since 1.5
625 */
626 public Annotation[] getDeclaredAnnotations() {
627 return declaredAnnotations().values().toArray(
628 EMPTY_ANNOTATION_ARRAY);
629 }
630
631 private transient Map<Class, Annotation> declaredAnnotations;
632
633 private synchronized Map<Class, Annotation> declaredAnnotations() {
634 if (declaredAnnotations == null) {
635 declaredAnnotations = AnnotationParser.parseAnnotations(
636 annotations, sun.misc.SharedSecrets
637 .getJavaLangAccess().getConstantPool(
638 getDeclaringClass()),
639 getDeclaringClass());
640 }
641 return declaredAnnotations;
642 }
643
644 /**
645 * Returns an array of arrays that represent the annotations on the formal
646 * parameters, in declaration order, of the method represented by
647 * this {@code Constructor} object. (Returns an array of length zero if the
648 * underlying method is parameterless. If the method has one or more
649 * parameters, a nested array of length zero is returned for each parameter
650 * with no annotations.) The annotation objects contained in the returned
651 * arrays are serializable. The caller of this method is free to modify
652 * the returned arrays; it will have no effect on the arrays returned to
653 * other callers.
654 *
655 * @return an array of arrays that represent the annotations on the formal
656 * parameters, in declaration order, of the method represented by this
657 * Constructor object
658 * @since 1.5
659 */
660 public Annotation[][] getParameterAnnotations() {
661 int numParameters = parameterTypes.length;
662 if (parameterAnnotations == null)
663 return new Annotation[numParameters][0];
664
665 Annotation[][] result = AnnotationParser
666 .parseParameterAnnotations(parameterAnnotations,
667 sun.misc.SharedSecrets.getJavaLangAccess()
668 .getConstantPool(getDeclaringClass()),
669 getDeclaringClass());
670 if (result.length != numParameters) {
671 Class<?> declaringClass = getDeclaringClass();
672 if (declaringClass.isEnum()
673 || declaringClass.isAnonymousClass()
674 || declaringClass.isLocalClass())
675 ; // Can't do reliable parameter counting
676 else {
677 if (!declaringClass.isMemberClass() || // top-level
678 // Check for the enclosing instance parameter for
679 // non-static member classes
680 (declaringClass.isMemberClass()
681 && ((declaringClass.getModifiers() & Modifier.STATIC) == 0) && result.length + 1 != numParameters)) {
682 throw new AnnotationFormatError(
683 "Parameter annotations don't match number of parameters");
684 }
685 }
686 }
687 return result;
688 }
689 }
|