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 * @return a string describing this {@code Executable}, including 388 * any type parameters 389 */ 390 public abstract String toGenericString(); 391 392 /** 393 * Returns {@code true} if this executable was declared to take a 394 * variable number of arguments; returns {@code false} otherwise. 395 * 396 * @return {@code true} if an only if this executable was declared 397 * to take a variable number of arguments. 398 */ 399 public boolean isVarArgs() { 400 return (getModifiers() & Modifier.VARARGS) != 0; 401 } 402 403 /** 404 * Returns {@code true} if this executable is a synthetic 405 * construct; returns {@code false} otherwise. 406 * 407 * @return true if and only if this executable is a synthetic 408 * construct as defined by 409 * <cite>The Java™ Language Specification</cite>. 410 * @jls 13.1 The Form of a Binary 411 */ 412 public boolean isSynthetic() { 413 return Modifier.isSynthetic(getModifiers()); 414 } 415 416 /** 417 * Returns an array of arrays that represent the annotations on 418 * the formal parameters, in declaration order, of the executable 419 * represented by this object. (Returns an array of length zero if 420 * the underlying executable is parameterless. If the executable has 421 * one or more parameters, a nested array of length zero is 422 * returned for each parameter with no annotations.) The 423 * annotation objects contained in the returned arrays are 424 * serializable. The caller of this method is free to modify the 425 * returned arrays; it will have no effect on the arrays returned 426 * to other callers. 427 * 428 * @return an array of arrays that represent the annotations on the formal 429 * parameters, in declaration order, of the executable represented by this 430 * object 431 */ 432 public abstract Annotation[][] getParameterAnnotations(); 433 434 Annotation[][] sharedGetParameterAnnotations(Class<?>[] parameterTypes, 435 byte[] parameterAnnotations) { 436 int numParameters = parameterTypes.length; 437 if (parameterAnnotations == null) 438 return new Annotation[numParameters][0]; 439 440 Annotation[][] result = parseParameterAnnotations(parameterAnnotations); 441 442 if (result.length != numParameters) 443 handleParameterNumberMismatch(result.length, numParameters); 444 return result; 445 } 446 447 abstract void handleParameterNumberMismatch(int resultLength, int numParameters); 448 449 /** 450 * {@inheritDoc} 451 * @throws NullPointerException {@inheritDoc} 452 */ 453 public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { 454 Objects.requireNonNull(annotationClass); 455 return annotationClass.cast(declaredAnnotations().get(annotationClass)); 456 } 457 458 /** 459 * {@inheritDoc} 460 * @throws NullPointerException {@inheritDoc} 461 * @since 1.8 462 */ 463 @Override 464 public <T extends Annotation> T[] getAnnotationsByType(Class<T> annotationClass) { 465 Objects.requireNonNull(annotationClass); 466 467 return AnnotationSupport.getMultipleAnnotations(declaredAnnotations(), annotationClass); 468 } 469 470 /** 471 * {@inheritDoc} 472 */ 473 public Annotation[] getDeclaredAnnotations() { 474 return AnnotationParser.toArray(declaredAnnotations()); 475 } 476 477 private transient Map<Class<? extends Annotation>, Annotation> declaredAnnotations; 478 479 private synchronized Map<Class<? extends Annotation>, Annotation> declaredAnnotations() { 480 if (declaredAnnotations == null) { 481 declaredAnnotations = AnnotationParser.parseAnnotations( 482 getAnnotationBytes(), 483 sun.misc.SharedSecrets.getJavaLangAccess(). 484 getConstantPool(getDeclaringClass()), 485 getDeclaringClass()); 486 } 487 return declaredAnnotations; 488 } 489 490 /** 491 * Returns an AnnotatedType object that represents the use of a type to 492 * specify the return type of the method/constructor represented by this 493 * Executable. 494 * 495 * If this Executable represents a constructor, the AnnotatedType object 496 * represents the type of the constructed object. 497 * 498 * If this Executable represents a method, the AnnotatedType object 499 * represents the use of a type to specify the return type of the method. 500 * 501 * @return an object representing the return type of this method 502 * or constructor 503 * @since 1.8 504 */ 505 public abstract AnnotatedType getAnnotatedReturnType(); 506 507 /* Helper for subclasses of Executable. 508 * 509 * Returns an AnnotatedType object that represents the use of a type to 510 * specify the return type of the method/constructor represented by this 511 * Executable. 512 * 513 * @since 1.8 514 */ 515 AnnotatedType getAnnotatedReturnType0(Type returnType) { 516 return TypeAnnotationParser.buildAnnotatedType(getTypeAnnotationBytes(), 517 sun.misc.SharedSecrets.getJavaLangAccess(). 518 getConstantPool(getDeclaringClass()), 519 this, 520 getDeclaringClass(), 521 returnType, 522 TypeAnnotation.TypeAnnotationTarget.METHOD_RETURN); 523 } 524 525 /** 526 * Returns an AnnotatedType object that represents the use of a type to 527 * specify the receiver type of the method/constructor represented by this 528 * Executable. The receiver type of a method/constructor is available only 529 * if the method/constructor declares a formal parameter called 'this'. 530 * 531 * Returns null if this Executable represents a constructor or instance 532 * method that either declares no formal parameter called 'this', or 533 * declares a formal parameter called 'this' with no annotations on its 534 * type. 535 * 536 * Returns null if this Executable represents a static method. 537 * 538 * @return an object representing the receiver type of the 539 * method or constructor represented by this Executable 540 * 541 * @since 1.8 542 */ 543 public AnnotatedType getAnnotatedReceiverType() { 544 return TypeAnnotationParser.buildAnnotatedType(getTypeAnnotationBytes(), 545 sun.misc.SharedSecrets.getJavaLangAccess(). 546 getConstantPool(getDeclaringClass()), 547 this, 548 getDeclaringClass(), 549 getDeclaringClass(), 550 TypeAnnotation.TypeAnnotationTarget.METHOD_RECEIVER); 551 } 552 553 /** 554 * Returns an array of AnnotatedType objects that represent the use of 555 * types to specify formal parameter types of the method/constructor 556 * represented by this Executable. The order of the objects in the array 557 * corresponds to the order of the formal parameter types in the 558 * declaration of the method/constructor. 559 * 560 * Returns an array of length 0 if the method/constructor declares no 561 * parameters. 562 * 563 * @return an array of objects representing the types of the 564 * formal parameters of this method or constructor 565 * 566 * @since 1.8 567 */ 568 public AnnotatedType[] getAnnotatedParameterTypes() { 569 return TypeAnnotationParser.buildAnnotatedTypes(getTypeAnnotationBytes(), 570 sun.misc.SharedSecrets.getJavaLangAccess(). 571 getConstantPool(getDeclaringClass()), 572 this, 573 getDeclaringClass(), 574 getParameterTypes(), 575 TypeAnnotation.TypeAnnotationTarget.METHOD_FORMAL_PARAMETER); 576 } 577 578 /** 579 * Returns an array of AnnotatedType objects that represent the use of 580 * types to specify the declared exceptions of the method/constructor 581 * represented by this Executable. The order of the objects in the array 582 * corresponds to the order of the exception types in the declaration of 583 * the method/constructor. 584 * 585 * Returns an array of length 0 if the method/constructor declares no 586 * exceptions. 587 * 588 * @return an array of objects representing the declared 589 * exceptions of this method or constructor 590 * 591 * @since 1.8 592 */ 593 public AnnotatedType[] getAnnotatedExceptionTypes() { 594 return TypeAnnotationParser.buildAnnotatedTypes(getTypeAnnotationBytes(), 595 sun.misc.SharedSecrets.getJavaLangAccess(). 596 getConstantPool(getDeclaringClass()), 597 this, 598 getDeclaringClass(), 599 getGenericExceptionTypes(), 600 TypeAnnotation.TypeAnnotationTarget.THROWS); 601 } 602 603 }