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