1 /* 2 * Copyright (c) 2012, 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 java.lang.annotation.*; 29 import java.util.Map; 30 import java.util.Objects; 31 import sun.reflect.annotation.AnnotationParser; 32 import sun.reflect.annotation.AnnotationSupport; 33 import sun.reflect.annotation.TypeAnnotationParser; 34 import sun.reflect.annotation.TypeAnnotation; 35 import sun.reflect.generics.repository.ConstructorRepository; 36 37 /** 38 * A shared superclass for the common functionality of {@link Method} 39 * and {@link Constructor}. 40 * 41 * @since 1.8 42 */ 43 public abstract class Executable extends AccessibleObject 44 implements Member, GenericDeclaration { 45 /* 46 * Only grant package-visibility to the constructor. 47 */ 48 Executable() {} 49 50 /** 51 * Accessor method to allow code sharing 52 */ 53 abstract byte[] getAnnotationBytes(); 54 abstract byte[] getTypeAnnotationBytes(); 55 56 /** 57 * Does the Executable have generic information. 58 */ 59 abstract boolean hasGenericInformation(); 60 61 abstract ConstructorRepository getGenericInfo(); 62 63 boolean equalParamTypes(Class<?>[] params1, Class<?>[] params2) { 64 /* Avoid unnecessary cloning */ 65 if (params1.length == params2.length) { 66 for (int i = 0; i < params1.length; i++) { 67 if (params1[i] != params2[i]) 68 return false; 69 } 70 return true; 71 } 72 return false; 73 } 74 75 Annotation[][] parseParameterAnnotations(byte[] parameterAnnotations) { 76 return AnnotationParser.parseParameterAnnotations( 77 parameterAnnotations, 78 sun.misc.SharedSecrets.getJavaLangAccess(). 79 getConstantPool(getDeclaringClass()), 80 getDeclaringClass()); 81 } 82 83 void separateWithCommas(Class<?>[] types, StringBuilder sb) { 84 for (int j = 0; j < types.length; j++) { 85 sb.append(types[j].getTypeName()); 86 if (j < (types.length - 1)) 87 sb.append(","); 88 } 89 90 } 91 92 void printModifiersIfNonzero(StringBuilder sb, int mask, boolean isDefault) { 93 int mod = getModifiers() & mask; 94 95 if (mod != 0 && !isDefault) { 96 sb.append(Modifier.toString(mod)).append(' '); 97 } else { 98 int access_mod = mod & Modifier.ACCESS_MODIFIERS; 99 if (access_mod != 0) 100 sb.append(Modifier.toString(access_mod)).append(' '); 101 if (isDefault) 102 sb.append("default "); 103 mod = (mod & ~Modifier.ACCESS_MODIFIERS); 104 if (mod != 0) 105 sb.append(Modifier.toString(mod)).append(' '); 106 } 107 } 108 109 String sharedToString(int modifierMask, 110 boolean isDefault, 111 Class<?>[] parameterTypes, 112 Class<?>[] exceptionTypes) { 113 try { 114 StringBuilder sb = new StringBuilder(); 115 116 printModifiersIfNonzero(sb, modifierMask, isDefault); 117 specificToStringHeader(sb); 118 119 sb.append('('); 120 separateWithCommas(parameterTypes, sb); 121 sb.append(')'); 122 if (exceptionTypes.length > 0) { 123 sb.append(" throws "); 124 separateWithCommas(exceptionTypes, sb); 125 } 126 return sb.toString(); 127 } catch (Exception e) { 128 return "<" + e + ">"; 129 } 130 } 131 132 /** 133 * Generate toString header information specific to a method or 134 * constructor. 135 */ 136 abstract void specificToStringHeader(StringBuilder sb); 137 138 String sharedToGenericString(int modifierMask, boolean isDefault) { 139 try { 140 StringBuilder sb = new StringBuilder(); 141 142 printModifiersIfNonzero(sb, modifierMask, isDefault); 143 144 TypeVariable<?>[] typeparms = getTypeParameters(); 145 if (typeparms.length > 0) { 146 boolean first = true; 147 sb.append('<'); 148 for(TypeVariable<?> typeparm: typeparms) { 149 if (!first) 150 sb.append(','); 151 // Class objects can't occur here; no need to test 152 // and call Class.getName(). 153 sb.append(typeparm.toString()); 154 first = false; 155 } 156 sb.append("> "); 157 } 158 159 specificToGenericStringHeader(sb); 160 161 sb.append('('); 162 Type[] params = getGenericParameterTypes(); 163 for (int j = 0; j < params.length; j++) { 164 String param = params[j].getTypeName(); 165 if (isVarArgs() && (j == params.length - 1)) // replace T[] with T... 166 param = param.replaceFirst("\\[\\]$", "..."); 167 sb.append(param); 168 if (j < (params.length - 1)) 169 sb.append(','); 170 } 171 sb.append(')'); 172 Type[] exceptions = getGenericExceptionTypes(); 173 if (exceptions.length > 0) { 174 sb.append(" throws "); 175 for (int k = 0; k < exceptions.length; k++) { 176 sb.append((exceptions[k] instanceof Class)? 177 ((Class)exceptions[k]).getName(): 178 exceptions[k].toString()); 179 if (k < (exceptions.length - 1)) 180 sb.append(','); 181 } 182 } 183 return sb.toString(); 184 } catch (Exception e) { 185 return "<" + e + ">"; 186 } 187 } 188 189 /** 190 * Generate toGenericString header information specific to a 191 * method or constructor. 192 */ 193 abstract void specificToGenericStringHeader(StringBuilder sb); 194 195 /** 196 * Returns the {@code Class} object representing the class or interface 197 * that declares the executable represented by this object. 198 */ 199 public abstract Class<?> getDeclaringClass(); 200 201 /** 202 * Returns the name of the executable represented by this object. 203 */ 204 public abstract String getName(); 205 206 /** 207 * Returns the Java language {@linkplain Modifier modifiers} for 208 * the executable represented by this object. 209 */ 210 public abstract int getModifiers(); 211 212 /** 213 * Returns an array of {@code TypeVariable} objects that represent the 214 * type variables declared by the generic declaration represented by this 215 * {@code GenericDeclaration} object, in declaration order. Returns an 216 * array of length 0 if the underlying generic declaration declares no type 217 * variables. 218 * 219 * @return an array of {@code TypeVariable} objects that represent 220 * the type variables declared by this generic declaration 221 * @throws GenericSignatureFormatError if the generic 222 * signature of this generic declaration does not conform to 223 * the format specified in 224 * <cite>The Java™ Virtual Machine Specification</cite> 225 */ 226 public abstract TypeVariable<?>[] getTypeParameters(); 227 228 /** 229 * Returns an array of {@code Class} objects that represent the formal 230 * parameter types, in declaration order, of the executable 231 * represented by this object. Returns an array of length 232 * 0 if the underlying executable takes no parameters. 233 * 234 * @return the parameter types for the executable this object 235 * represents 236 */ 237 public abstract Class<?>[] getParameterTypes(); 238 239 /** 240 * Returns the number of formal parameters (whether explicitly 241 * declared or implicitly declared or neither) for the executable 242 * represented by this object. 243 * 244 * @return The number of formal parameters for the executable this 245 * object represents 246 */ 247 public int getParameterCount() { 248 throw new AbstractMethodError(); 249 } 250 251 /** 252 * Returns an array of {@code Type} objects that represent the formal 253 * parameter types, in declaration order, of the executable represented by 254 * this object. Returns an array of length 0 if the 255 * underlying executable takes no parameters. 256 * 257 * <p>If a formal parameter type is a parameterized type, 258 * the {@code Type} object returned for it must accurately reflect 259 * the actual type parameters used in the source code. 260 * 261 * <p>If a formal parameter type is a type variable or a parameterized 262 * type, it is created. Otherwise, it is resolved. 263 * 264 * @return an array of {@code Type}s that represent the formal 265 * parameter types of the underlying executable, in declaration order 266 * @throws GenericSignatureFormatError 267 * if the generic method signature does not conform to the format 268 * specified in 269 * <cite>The Java™ Virtual Machine Specification</cite> 270 * @throws TypeNotPresentException if any of the parameter 271 * types of the underlying executable refers to a non-existent type 272 * declaration 273 * @throws MalformedParameterizedTypeException if any of 274 * the underlying executable's parameter types refer to a parameterized 275 * type that cannot be instantiated for any reason 276 */ 277 public Type[] getGenericParameterTypes() { 278 if (hasGenericInformation()) 279 return getGenericInfo().getParameterTypes(); 280 else 281 return getParameterTypes(); 282 } 283 284 /** 285 * Returns an array of {@code Parameter} objects that represent 286 * all the parameters to the underlying executable represented by 287 * this object. Returns an array of length 0 if the executable 288 * has no parameters. 289 * 290 * The parameters of the underlying executable do not necessarily 291 * have unique names, or names that are legal identifiers in the 292 * Java programming language (JLS 3.8). 293 * 294 * @return an array of {@code Parameter} objects representing all 295 * the parameters to the executable this object represents 296 */ 297 public Parameter[] getParameters() { 298 // TODO: This may eventually need to be guarded by security 299 // mechanisms similar to those in Field, Method, etc. 300 // 301 // Need to copy the cached array to prevent users from messing 302 // with it. Since parameters are immutable, we can 303 // shallow-copy. 304 return privateGetParameters().clone(); 305 } 306 307 private Parameter[] synthesizeAllParams() { 308 final int realparams = getParameterCount(); 309 final Parameter[] out = new Parameter[realparams]; 310 for (int i = 0; i < realparams; i++) 311 // TODO: is there a way to synthetically derive the 312 // modifiers? Probably not in the general case, since 313 // we'd have no way of knowing about them, but there 314 // may be specific cases. 315 out[i] = new Parameter("arg" + i, 0, this, i); 316 return out; 317 } 318 319 private Parameter[] privateGetParameters() { 320 // Use tmp to avoid multiple writes to a volatile. 321 Parameter[] tmp = parameters; 322 323 if (tmp == null) { 324 325 // Otherwise, go to the JVM to get them 326 tmp = getParameters0(); 327 328 // If we get back nothing, then synthesize parameters 329 if (tmp == null) 330 tmp = synthesizeAllParams(); 331 332 parameters = tmp; 333 } 334 335 return tmp; 336 } 337 338 private transient volatile Parameter[] parameters; 339 340 private native Parameter[] getParameters0(); 341 342 /** 343 * Returns an array of {@code Class} objects that represent the 344 * types of exceptions declared to be thrown by the underlying 345 * executable represented by this object. Returns an array of 346 * length 0 if the executable declares no exceptions in its {@code 347 * throws} clause. 348 * 349 * @return the exception types declared as being thrown by the 350 * executable this object represents 351 */ 352 public abstract Class<?>[] getExceptionTypes(); 353 354 /** 355 * Returns an array of {@code Type} objects that represent the 356 * exceptions declared to be thrown by this executable object. 357 * Returns an array of length 0 if the underlying executable declares 358 * no exceptions in its {@code throws} clause. 359 * 360 * <p>If an exception type is a type variable or a parameterized 361 * type, it is created. Otherwise, it is resolved. 362 * 363 * @return an array of Types that represent the exception types 364 * thrown by the underlying executable 365 * @throws GenericSignatureFormatError 366 * if the generic method signature does not conform to the format 367 * specified in 368 * <cite>The Java™ Virtual Machine Specification</cite> 369 * @throws TypeNotPresentException if the underlying executable's 370 * {@code throws} clause refers to a non-existent type declaration 371 * @throws MalformedParameterizedTypeException if 372 * the underlying executable's {@code throws} clause refers to a 373 * parameterized type that cannot be instantiated for any reason 374 */ 375 public Type[] getGenericExceptionTypes() { 376 Type[] result; 377 if (hasGenericInformation() && 378 ((result = getGenericInfo().getExceptionTypes()).length > 0)) 379 return result; 380 else 381 return getExceptionTypes(); 382 } 383 384 /** 385 * Returns a string describing this {@code Executable}, including 386 * any type parameters. 387 */ 388 public abstract String toGenericString(); 389 390 /** 391 * Returns {@code true} if this executable was declared to take a 392 * variable number of arguments; returns {@code false} otherwise. 393 * 394 * @return {@code true} if an only if this executable was declared 395 * to take a variable number of arguments. 396 */ 397 public boolean isVarArgs() { 398 return (getModifiers() & Modifier.VARARGS) != 0; 399 } 400 401 /** 402 * Returns {@code true} if this executable is a synthetic 403 * construct; returns {@code false} otherwise. 404 * 405 * @return true if and only if this executable is a synthetic 406 * construct as defined by 407 * <cite>The Java™ Language Specification</cite>. 408 * @jls 13.1 The Form of a Binary 409 */ 410 public boolean isSynthetic() { 411 return Modifier.isSynthetic(getModifiers()); 412 } 413 414 /** 415 * Returns an array of arrays that represent the annotations on 416 * the formal parameters, in declaration order, of the executable 417 * represented by this object. (Returns an array of length zero if 418 * the underlying executable is parameterless. If the executable has 419 * one or more parameters, a nested array of length zero is 420 * returned for each parameter with no annotations.) The 421 * annotation objects contained in the returned arrays are 422 * serializable. The caller of this method is free to modify the 423 * returned arrays; it will have no effect on the arrays returned 424 * to other callers. 425 * 426 * @return an array of arrays that represent the annotations on the formal 427 * parameters, in declaration order, of the executable represented by this 428 * object 429 */ 430 public abstract Annotation[][] getParameterAnnotations(); 431 432 Annotation[][] sharedGetParameterAnnotations(Class<?>[] parameterTypes, 433 byte[] parameterAnnotations) { 434 int numParameters = parameterTypes.length; 435 if (parameterAnnotations == null) 436 return new Annotation[numParameters][0]; 437 438 Annotation[][] result = parseParameterAnnotations(parameterAnnotations); 439 440 if (result.length != numParameters) 441 handleParameterNumberMismatch(result.length, numParameters); 442 return result; 443 } 444 445 abstract void handleParameterNumberMismatch(int resultLength, int numParameters); 446 447 /** 448 * {@inheritDoc} 449 * @throws NullPointerException {@inheritDoc} 450 */ 451 public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { 452 Objects.requireNonNull(annotationClass); 453 return annotationClass.cast(declaredAnnotations().get(annotationClass)); 454 } 455 456 /** 457 * {@inheritDoc} 458 * @throws NullPointerException {@inheritDoc} 459 * @since 1.8 460 */ 461 @Override 462 public <T extends Annotation> T[] getAnnotationsByType(Class<T> annotationClass) { 463 Objects.requireNonNull(annotationClass); 464 465 return AnnotationSupport.getMultipleAnnotations(declaredAnnotations(), annotationClass); 466 } 467 468 /** 469 * {@inheritDoc} 470 */ 471 public Annotation[] getDeclaredAnnotations() { 472 return AnnotationParser.toArray(declaredAnnotations()); 473 } 474 475 private transient Map<Class<? extends Annotation>, Annotation> declaredAnnotations; 476 477 private synchronized Map<Class<? extends Annotation>, Annotation> declaredAnnotations() { 478 if (declaredAnnotations == null) { 479 declaredAnnotations = AnnotationParser.parseAnnotations( 480 getAnnotationBytes(), 481 sun.misc.SharedSecrets.getJavaLangAccess(). 482 getConstantPool(getDeclaringClass()), 483 getDeclaringClass()); 484 } 485 return declaredAnnotations; 486 } 487 488 /** 489 * Returns an AnnotatedType object that represents the use of a type to 490 * specify the return type of the method/constructor represented by this 491 * Executable. 492 * 493 * If this Executable represents a constructor, the AnnotatedType object 494 * represents the type of the constructed object. 495 * 496 * If this Executable represents a method, the AnnotatedType object 497 * represents the use of a type to specify the return type of the method. 498 * 499 * @since 1.8 500 */ 501 public abstract AnnotatedType getAnnotatedReturnType(); 502 503 /* Helper for subclasses of Executable. 504 * 505 * Returns an AnnotatedType object that represents the use of a type to 506 * specify the return type of the method/constructor represented by this 507 * Executable. 508 * 509 * @since 1.8 510 */ 511 AnnotatedType getAnnotatedReturnType0(Type returnType) { 512 return TypeAnnotationParser.buildAnnotatedType(getTypeAnnotationBytes(), 513 sun.misc.SharedSecrets.getJavaLangAccess(). 514 getConstantPool(getDeclaringClass()), 515 this, 516 getDeclaringClass(), 517 returnType, 518 TypeAnnotation.TypeAnnotationTarget.METHOD_RETURN); 519 } 520 521 /** 522 * Returns an AnnotatedType object that represents the use of a type to 523 * specify the receiver type of the method/constructor represented by this 524 * Executable. The receiver type of a method/constructor is available only 525 * if the method/constructor declares a formal parameter called 'this'. 526 * 527 * Returns null if this Executable represents a constructor or instance 528 * method that either declares no formal parameter called 'this', or 529 * declares a formal parameter called 'this' with no annotations on its 530 * type. 531 * 532 * Returns null if this Executable represents a static method. 533 * 534 * @since 1.8 535 */ 536 public AnnotatedType getAnnotatedReceiverType() { 537 return TypeAnnotationParser.buildAnnotatedType(getTypeAnnotationBytes(), 538 sun.misc.SharedSecrets.getJavaLangAccess(). 539 getConstantPool(getDeclaringClass()), 540 this, 541 getDeclaringClass(), 542 getDeclaringClass(), 543 TypeAnnotation.TypeAnnotationTarget.METHOD_RECEIVER); 544 } 545 546 /** 547 * Returns an array of AnnotatedType objects that represent the use of 548 * types to specify formal parameter types of the method/constructor 549 * represented by this Executable. The order of the objects in the array 550 * corresponds to the order of the formal parameter types in the 551 * declaration of the method/constructor. 552 * 553 * Returns an array of length 0 if the method/constructor declares no 554 * parameters. 555 * 556 * @since 1.8 557 */ 558 public AnnotatedType[] getAnnotatedParameterTypes() { 559 return TypeAnnotationParser.buildAnnotatedTypes(getTypeAnnotationBytes(), 560 sun.misc.SharedSecrets.getJavaLangAccess(). 561 getConstantPool(getDeclaringClass()), 562 this, 563 getDeclaringClass(), 564 getParameterTypes(), 565 TypeAnnotation.TypeAnnotationTarget.METHOD_FORMAL_PARAMETER); 566 } 567 568 /** 569 * Returns an array of AnnotatedType objects that represent the use of 570 * types to specify the declared exceptions of the method/constructor 571 * represented by this Executable. The order of the objects in the array 572 * corresponds to the order of the exception types in the declaration of 573 * the method/constructor. 574 * 575 * Returns an array of length 0 if the method/constructor declares no 576 * exceptions. 577 * 578 * @since 1.8 579 */ 580 public AnnotatedType[] getAnnotatedExceptionTypes() { 581 return TypeAnnotationParser.buildAnnotatedTypes(getTypeAnnotationBytes(), 582 sun.misc.SharedSecrets.getJavaLangAccess(). 583 getConstantPool(getDeclaringClass()), 584 this, 585 getDeclaringClass(), 586 getGenericExceptionTypes(), 587 TypeAnnotation.TypeAnnotationTarget.THROWS); 588 } 589 590 }