1 /* 2 * Copyright 1996-2006 Sun Microsystems, Inc. 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. Sun designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, 22 * CA 95054 USA or visit www.sun.com if you need additional information or 23 * have any questions. 24 */ 25 26 package java.lang.reflect; 27 28 import sun.reflect.ConstructorAccessor; 29 import sun.reflect.Reflection; 30 import sun.reflect.generics.repository.ConstructorRepository; 31 import sun.reflect.generics.factory.CoreReflectionFactory; 32 import sun.reflect.generics.factory.GenericsFactory; 33 import sun.reflect.generics.scope.ConstructorScope; 34 import java.lang.annotation.Annotation; 35 import java.util.Map; 36 import sun.reflect.annotation.AnnotationParser; 37 import java.lang.annotation.AnnotationFormatError; 38 import java.lang.reflect.Modifier; 39 40 /** 41 * {@code Constructor} provides information about, and access to, a single 42 * constructor for a class. 43 * 44 * <p>{@code Constructor} permits widening conversions to occur when matching the 45 * actual parameters to newInstance() with the underlying 46 * constructor's formal parameters, but throws an 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. 138 */ 139 Constructor<T> copy() { 140 // This routine enables sharing of ConstructorAccessor objects 141 // among Constructor objects which refer to the same underlying 142 // method in the VM. (All of this contortion is only necessary 143 // because of the "accessibility" bit in AccessibleObject, 144 // which implicitly requires that new java.lang.reflect 145 // objects be fabricated for each reflective call on Class 146 // objects.) 147 Constructor<T> res = new Constructor<T>(clazz, 148 parameterTypes, 149 exceptionTypes, modifiers, slot, 150 signature, 151 annotations, 152 parameterAnnotations); 153 res.root = this; 154 // Might as well eagerly propagate this if already present 155 res.constructorAccessor = constructorAccessor; 156 return res; 157 } 158 159 /** 160 * Returns the {@code Class} object representing the class that declares 161 * the constructor represented by this {@code Constructor} object. 162 */ 163 public Class<T> getDeclaringClass() { 164 return clazz; 165 } 166 167 /** 168 * Returns the name of this constructor, as a string. This is 169 * always the same as the simple name of the constructor's declaring 170 * class. 171 */ 172 public String getName() { 173 return getDeclaringClass().getName(); 174 } 175 176 /** 177 * Returns the Java language modifiers for the constructor 178 * represented by this {@code Constructor} object, as an integer. The 179 * {@code Modifier} class should be used to decode the modifiers. 180 * 181 * @see Modifier 182 */ 183 public int getModifiers() { 184 return modifiers; 185 } 186 187 /** 188 * Returns an array of {@code TypeVariable} objects that represent the 189 * type variables declared by the generic declaration represented by this 190 * {@code GenericDeclaration} object, in declaration order. Returns an 191 * array of length 0 if the underlying generic declaration declares no type 192 * variables. 193 * 194 * @return an array of {@code TypeVariable} objects that represent 195 * the type variables declared by this generic declaration 196 * @throws GenericSignatureFormatError if the generic 197 * signature of this generic declaration does not conform to 198 * the format specified in the Java Virtual Machine Specification, 199 * 3rd edition 200 * @since 1.5 201 */ 202 public TypeVariable<Constructor<T>>[] getTypeParameters() { 203 if (getSignature() != null) { 204 return (TypeVariable<Constructor<T>>[])getGenericInfo().getTypeParameters(); 205 } else 206 return (TypeVariable<Constructor<T>>[])new TypeVariable[0]; 207 } 208 209 210 /** 211 * Returns an array of {@code Class} objects that represent the formal 212 * parameter types, in declaration order, of the constructor 213 * represented by this {@code Constructor} object. Returns an array of 214 * length 0 if the underlying constructor takes no parameters. 215 * 216 * @return the parameter types for the constructor this object 217 * represents 218 */ 219 public Class<?>[] getParameterTypes() { 220 return (Class<?>[]) parameterTypes.clone(); 221 } 222 223 224 /** 225 * Returns an array of {@code Type} objects that represent the formal 226 * parameter types, in declaration order, of the method represented by 227 * this {@code Constructor} object. Returns an array of length 0 if the 228 * underlying method takes no parameters. 229 * 230 * <p>If a formal parameter type is a parameterized type, 231 * the {@code Type} object returned for it must accurately reflect 232 * the actual type parameters used in the source code. 233 * 234 * <p>If a formal parameter type is a type variable or a parameterized 235 * type, it is created. Otherwise, it is resolved. 236 * 237 * @return an array of {@code Type}s that represent the formal 238 * parameter types of the underlying method, in declaration order 239 * @throws GenericSignatureFormatError 240 * if the generic method signature does not conform to the format 241 * specified in the Java Virtual Machine Specification, 3rd edition 242 * @throws TypeNotPresentException if any of the parameter 243 * types of the underlying method refers to a non-existent type 244 * declaration 245 * @throws MalformedParameterizedTypeException if any of 246 * the underlying method's parameter types refer to a parameterized 247 * type that cannot be instantiated for any reason 248 * @since 1.5 249 */ 250 public Type[] getGenericParameterTypes() { 251 if (getSignature() != null) 252 return getGenericInfo().getParameterTypes(); 253 else 254 return getParameterTypes(); 255 } 256 257 258 /** 259 * Returns an array of {@code Class} objects that represent the types 260 * of exceptions declared to be thrown by the underlying constructor 261 * represented by this {@code Constructor} object. Returns an array of 262 * length 0 if the constructor declares no exceptions in its {@code throws} clause. 263 * 264 * @return the exception types declared as being thrown by the 265 * constructor this object represents 266 */ 267 public Class<?>[] getExceptionTypes() { 268 return (Class<?>[])exceptionTypes.clone(); 269 } 270 271 272 /** 273 * Returns an array of {@code Type} objects that represent the 274 * exceptions declared to be thrown by this {@code Constructor} object. 275 * Returns an array of length 0 if the underlying method declares 276 * no exceptions in its {@code throws} clause. 277 * 278 * <p>If an exception type is a type variable or a parameterized 279 * type, it is created. Otherwise, it is resolved. 280 * 281 * @return an array of Types that represent the exception types 282 * thrown by the underlying method 283 * @throws GenericSignatureFormatError 284 * if the generic method signature does not conform to the format 285 * specified in the Java Virtual Machine Specification, 3rd edition 286 * @throws TypeNotPresentException if the underlying method's 287 * {@code throws} clause refers to a non-existent type declaration 288 * @throws MalformedParameterizedTypeException if 289 * the underlying method's {@code throws} clause refers to a 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 } 335 336 /** 337 * Returns a string describing this {@code Constructor}. The string is 338 * formatted as the constructor access modifiers, if any, 339 * followed by the fully-qualified name of the declaring class, 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 388 * declaring class, followed by a parenthesized, comma-separated 389 * list of the constructor's generic formal parameter types. 390 * 391 * If this constructor was declared to take a variable number of 392 * arguments, instead of denoting the last parameter as 393 * "<tt><i>Type</i>[]</tt>", it is denoted as 394 * "<tt><i>Type</i>...</tt>". 395 * 396 * A space is used to separate access modifiers from one another 397 * and from the type parameters or return type. If there are no 398 * type parameters, the type parameter list is elided; if the type 399 * parameter list is present, a space separates the list from the 400 * class name. If the constructor is declared to throw 401 * exceptions, the parameter list is followed by a space, followed 402 * by the word "{@code throws}" followed by a 403 * comma-separated list of the thrown exception types. 404 * 405 * <p>The only possible modifiers for constructors are the access 406 * modifiers {@code public}, {@code protected} or 407 * {@code private}. Only one of these may appear, or none if the 408 * constructor has default (package) access. 409 * 410 * @return a string describing this {@code Constructor}, 411 * include type parameters 412 * 413 * @since 1.5 414 */ 415 public String toGenericString() { 416 try { 417 StringBuilder sb = new StringBuilder(); 418 int mod = getModifiers() & Modifier.constructorModifiers(); 419 if (mod != 0) { 420 sb.append(Modifier.toString(mod) + " "); 421 } 422 TypeVariable<?>[] typeparms = getTypeParameters(); 423 if (typeparms.length > 0) { 424 boolean first = true; 425 sb.append("<"); 426 for(TypeVariable<?> typeparm: typeparms) { 427 if (!first) 428 sb.append(","); 429 // Class objects can't occur here; no need to test 430 // and call Class.getName(). 431 sb.append(typeparm.toString()); 432 first = false; 433 } 434 sb.append("> "); 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 476 * is 0, the supplied {@code initargs} array may be of length 0 or null. 477 * 478 * <p>If the constructor's declaring class is an inner class in a 479 * non-static context, the first argument to the constructor needs 480 * to be the enclosing instance; see <i>The Java Language 481 * Specification</i>, section 15.9.3. 482 * 483 * <p>If the required access and argument checks succeed and the 484 * instantiation will proceed, the constructor's declaring class 485 * is initialized if it has not already been initialized. 486 * 487 * <p>If the constructor completes normally, returns the newly 488 * created and initialized instance. 489 * 490 * @param initargs array of objects to be passed as arguments to 491 * the constructor call; values of primitive types are wrapped in 492 * a wrapper object of the appropriate type (e.g. a {@code float} 493 * in a {@link java.lang.Float Float}) 494 * 495 * @return a new object created by calling the constructor 496 * this object represents 497 * 498 * @exception IllegalAccessException if this {@code Constructor} object 499 * enforces Java language access control and the underlying 500 * constructor is inaccessible. 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 542 */ 543 public boolean isVarArgs() { 544 return (getModifiers() & Modifier.VARARGS) != 0; 545 } 546 547 /** 548 * Returns {@code true} if this constructor is a synthetic 549 * constructor; returns {@code false} otherwise. 550 * 551 * @return true if and only if this constructor is a synthetic 552 * constructor as defined by the Java Language Specification. 553 * @since 1.5 554 */ 555 public boolean isSynthetic() { 556 return Modifier.isSynthetic(getModifiers()); 557 } 558 559 // NOTE that there is no synchronization used here. It is correct 560 // (though not efficient) to generate more than one 561 // ConstructorAccessor for a given Constructor. However, avoiding 562 // synchronization will probably make the implementation more 563 // scalable. 564 private void acquireConstructorAccessor() { 565 // First check to see if one has been created yet, and take it 566 // if so. 567 ConstructorAccessor tmp = null; 568 if (root != null) tmp = root.getConstructorAccessor(); 569 if (tmp != null) { 570 constructorAccessor = tmp; 571 return; 572 } 573 // Otherwise fabricate one and propagate it up to the root 574 tmp = reflectionFactory.newConstructorAccessor(this); 575 setConstructorAccessor(tmp); 576 } 577 578 // Returns ConstructorAccessor for this Constructor object, not 579 // looking up the chain to the root 580 ConstructorAccessor getConstructorAccessor() { 581 return constructorAccessor; 582 } 583 584 // Sets the ConstructorAccessor for this Constructor object and 585 // (recursively) its root 586 void setConstructorAccessor(ConstructorAccessor accessor) { 587 constructorAccessor = accessor; 588 // Propagate up 589 if (root != null) { 590 root.setConstructorAccessor(accessor); 591 } 592 } 593 594 int getSlot() { 595 return slot; 596 } 597 598 String getSignature() { 599 return signature; 600 } 601 602 byte[] getRawAnnotations() { 603 return annotations; 604 } 605 606 byte[] getRawParameterAnnotations() { 607 return parameterAnnotations; 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 * 651 * @return an array of arrays that represent the annotations on the formal 652 * parameters, in declaration order, of the method represented by this 653 * Constructor object 654 * @since 1.5 655 */ 656 public Annotation[][] getParameterAnnotations() { 657 int numParameters = parameterTypes.length; 658 if (parameterAnnotations == null) 659 return new Annotation[numParameters][0]; 660 661 Annotation[][] result = AnnotationParser.parseParameterAnnotations( 662 parameterAnnotations, 663 sun.misc.SharedSecrets.getJavaLangAccess(). 664 getConstantPool(getDeclaringClass()), 665 getDeclaringClass()); 666 if (result.length != numParameters) { 667 Class<?> declaringClass = getDeclaringClass(); 668 if (declaringClass.isEnum() || 669 declaringClass.isAnonymousClass() || 670 declaringClass.isLocalClass() ) 671 ; // Can't do reliable parameter counting 672 else { 673 if (!declaringClass.isMemberClass() || // top-level 674 // Check for the enclosing instance parameter for 675 // non-static member classes 676 (declaringClass.isMemberClass() && 677 ((declaringClass.getModifiers() & Modifier.STATIC) == 0) && 678 result.length + 1 != numParameters) ) { 679 throw new AnnotationFormatError( 680 "Parameter annotations don't match number of parameters"); 681 } 682 } 683 } 684 return result; 685 } 686 }