GNU Classpath (0.92) | |
Frames | No Frames |
1: /* Class.java -- Representation of a Java class. 2: Copyright (C) 1998, 1999, 2000, 2002, 2003, 2004, 2005, 2006 3: Free Software Foundation 4: 5: This file is part of GNU Classpath. 6: 7: GNU Classpath is free software; you can redistribute it and/or modify 8: it under the terms of the GNU General Public License as published by 9: the Free Software Foundation; either version 2, or (at your option) 10: any later version. 11: 12: GNU Classpath is distributed in the hope that it will be useful, but 13: WITHOUT ANY WARRANTY; without even the implied warranty of 14: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 15: General Public License for more details. 16: 17: You should have received a copy of the GNU General Public License 18: along with GNU Classpath; see the file COPYING. If not, write to the 19: Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 20: 02110-1301 USA. 21: 22: Linking this library statically or dynamically with other modules is 23: making a combined work based on this library. Thus, the terms and 24: conditions of the GNU General Public License cover the whole 25: combination. 26: 27: As a special exception, the copyright holders of this library give you 28: permission to link this library with independent modules to produce an 29: executable, regardless of the license terms of these independent 30: modules, and to copy and distribute the resulting executable under 31: terms of your choice, provided that you also meet, for each linked 32: independent module, the terms and conditions of the license of that 33: module. An independent module is a module which is not derived from 34: or based on this library. If you modify this library, you may extend 35: this exception to your version of the library, but you are not 36: obligated to do so. If you do not wish to do so, delete this 37: exception statement from your version. */ 38: 39: package java.lang; 40: 41: import gnu.classpath.VMStackWalker; 42: import gnu.java.lang.reflect.ClassSignatureParser; 43: 44: import java.io.InputStream; 45: import java.io.ObjectStreamClass; 46: import java.io.Serializable; 47: import java.lang.annotation.Annotation; 48: import java.lang.reflect.Array; 49: import java.lang.reflect.AnnotatedElement; 50: import java.lang.reflect.Constructor; 51: import java.lang.reflect.Field; 52: import java.lang.reflect.GenericDeclaration; 53: import java.lang.reflect.GenericSignatureFormatError; 54: import java.lang.reflect.InvocationTargetException; 55: import java.lang.reflect.MalformedParameterizedTypeException; 56: import java.lang.reflect.Member; 57: import java.lang.reflect.Method; 58: import java.lang.reflect.Modifier; 59: import java.lang.reflect.Type; 60: import java.lang.reflect.TypeVariable; 61: import java.net.URL; 62: import java.security.AccessController; 63: import java.security.AllPermission; 64: import java.security.Permissions; 65: import java.security.PrivilegedAction; 66: import java.security.ProtectionDomain; 67: import java.util.ArrayList; 68: import java.util.Arrays; 69: import java.util.HashMap; 70: import java.util.HashSet; 71: 72: 73: /** 74: * A Class represents a Java type. There will never be multiple Class 75: * objects with identical names and ClassLoaders. Primitive types, array 76: * types, and void also have a Class object. 77: * 78: * <p>Arrays with identical type and number of dimensions share the same class. 79: * The array class ClassLoader is the same as the ClassLoader of the element 80: * type of the array (which can be null to indicate the bootstrap classloader). 81: * The name of an array class is <code>[<signature format>;</code>. 82: * <p> For example, 83: * String[]'s class is <code>[Ljava.lang.String;</code>. boolean, byte, 84: * short, char, int, long, float and double have the "type name" of 85: * Z,B,S,C,I,J,F,D for the purposes of array classes. If it's a 86: * multidimensioned array, the same principle applies: 87: * <code>int[][][]</code> == <code>[[[I</code>. 88: * 89: * <p>There is no public constructor - Class objects are obtained only through 90: * the virtual machine, as defined in ClassLoaders. 91: * 92: * @serialData Class objects serialize specially: 93: * <code>TC_CLASS ClassDescriptor</code>. For more serialization information, 94: * see {@link ObjectStreamClass}. 95: * 96: * @author John Keiser 97: * @author Eric Blake (ebb9@email.byu.edu) 98: * @author Tom Tromey (tromey@redhat.com) 99: * @author Andrew John Hughes (gnu_andrew@member.fsf.org) 100: * @author Tom Tromey (tromey@cygnus.com) 101: * @since 1.0 102: * @see ClassLoader 103: */ 104: public final class Class 105: implements Serializable, Type, AnnotatedElement, GenericDeclaration 106: { 107: /** 108: * Compatible with JDK 1.0+. 109: */ 110: private static final long serialVersionUID = 3206093459760846163L; 111: 112: /** 113: * Flag indicating a synthetic member. 114: * Note that this duplicates a constant in Modifier. 115: */ 116: private static final int SYNTHETIC = 0x1000; 117: 118: /** 119: * Flag indiciating an annotation class. 120: */ 121: private static final int ANNOTATION = 0x2000; 122: 123: /** 124: * Flag indicating an enum constant or an enum class. 125: * Note that this duplicates a constant in Modifier. 126: */ 127: private static final int ENUM = 0x4000; 128: 129: /** The class signers. */ 130: private Object[] signers = null; 131: /** The class protection domain. */ 132: private final transient ProtectionDomain pd; 133: 134: /* We use an inner class, so that Class doesn't have a static initializer */ 135: private static final class StaticData 136: { 137: static final ProtectionDomain unknownProtectionDomain; 138: 139: static 140: { 141: Permissions permissions = new Permissions(); 142: permissions.add(new AllPermission()); 143: unknownProtectionDomain = new ProtectionDomain(null, permissions); 144: } 145: } 146: 147: final transient Object vmdata; 148: 149: /** newInstance() caches the default constructor */ 150: private transient Constructor constructor; 151: 152: /** 153: * Class is non-instantiable from Java code; only the VM can create 154: * instances of this class. 155: */ 156: Class(Object vmdata) 157: { 158: this(vmdata, null); 159: } 160: 161: Class(Object vmdata, ProtectionDomain pd) 162: { 163: this.vmdata = vmdata; 164: // If the VM didn't supply a protection domain and the class is an array, 165: // we "inherit" the protection domain from the component type class. This 166: // saves the VM from having to worry about protection domains for array 167: // classes. 168: if (pd == null && isArray()) 169: this.pd = getComponentType().pd; 170: else 171: this.pd = pd; 172: } 173: 174: /** 175: * Use the classloader of the current class to load, link, and initialize 176: * a class. This is equivalent to your code calling 177: * <code>Class.forName(name, true, getClass().getClassLoader())</code>. 178: * 179: * @param name the name of the class to find 180: * @return the Class object representing the class 181: * @throws ClassNotFoundException if the class was not found by the 182: * classloader 183: * @throws LinkageError if linking the class fails 184: * @throws ExceptionInInitializerError if the class loads, but an exception 185: * occurs during initialization 186: */ 187: public static Class forName(String name) throws ClassNotFoundException 188: { 189: return VMClass.forName(name, true, VMStackWalker.getCallingClassLoader()); 190: } 191: 192: /** 193: * Use the specified classloader to load and link a class. If the loader 194: * is null, this uses the bootstrap class loader (provide the security 195: * check succeeds). Unfortunately, this method cannot be used to obtain 196: * the Class objects for primitive types or for void, you have to use 197: * the fields in the appropriate java.lang wrapper classes. 198: * 199: * <p>Calls <code>classloader.loadclass(name, initialize)</code>. 200: * 201: * @param name the name of the class to find 202: * @param initialize whether or not to initialize the class at this time 203: * @param classloader the classloader to use to find the class; null means 204: * to use the bootstrap class loader 205: * 206: * @return the class object for the given class 207: * 208: * @throws ClassNotFoundException if the class was not found by the 209: * classloader 210: * @throws LinkageError if linking the class fails 211: * @throws ExceptionInInitializerError if the class loads, but an exception 212: * occurs during initialization 213: * @throws SecurityException if the <code>classloader</code> argument 214: * is <code>null</code> and the caller does not have the 215: * <code>RuntimePermission("getClassLoader")</code> permission 216: * @see ClassLoader 217: * @since 1.2 218: */ 219: public static Class forName(String name, boolean initialize, 220: ClassLoader classloader) 221: throws ClassNotFoundException 222: { 223: if (classloader == null) 224: { 225: // Check if we may access the bootstrap classloader 226: SecurityManager sm = SecurityManager.current; 227: if (sm != null) 228: { 229: // Get the calling classloader 230: ClassLoader cl = VMStackWalker.getCallingClassLoader(); 231: if (cl != null) 232: sm.checkPermission(new RuntimePermission("getClassLoader")); 233: } 234: } 235: return VMClass.forName(name, initialize, classloader); 236: } 237: 238: /** 239: * Get all the public member classes and interfaces declared in this 240: * class or inherited from superclasses. This returns an array of length 241: * 0 if there are no member classes, including for primitive types. A 242: * security check may be performed, with 243: * <code>checkMemberAccess(this, Member.PUBLIC)</code> as well as 244: * <code>checkPackageAccess</code> both having to succeed. 245: * 246: * @return all public member classes in this class 247: * @throws SecurityException if the security check fails 248: * @since 1.1 249: */ 250: public Class[] getClasses() 251: { 252: memberAccessCheck(Member.PUBLIC); 253: return internalGetClasses(); 254: } 255: 256: /** 257: * Like <code>getClasses()</code> but without the security checks. 258: */ 259: private Class[] internalGetClasses() 260: { 261: ArrayList list = new ArrayList(); 262: list.addAll(Arrays.asList(getDeclaredClasses(true))); 263: Class superClass = getSuperclass(); 264: if (superClass != null) 265: list.addAll(Arrays.asList(superClass.internalGetClasses())); 266: return (Class[])list.toArray(new Class[list.size()]); 267: } 268: 269: /** 270: * Get the ClassLoader that loaded this class. If the class was loaded 271: * by the bootstrap classloader, this method will return null. 272: * If there is a security manager, and the caller's class loader is not 273: * an ancestor of the requested one, a security check of 274: * <code>RuntimePermission("getClassLoader")</code> 275: * must first succeed. Primitive types and void return null. 276: * 277: * @return the ClassLoader that loaded this class 278: * @throws SecurityException if the security check fails 279: * @see ClassLoader 280: * @see RuntimePermission 281: */ 282: public ClassLoader getClassLoader() 283: { 284: if (isPrimitive()) 285: return null; 286: 287: ClassLoader loader = VMClass.getClassLoader(this); 288: // Check if we may get the classloader 289: SecurityManager sm = SecurityManager.current; 290: if (loader != null && sm != null) 291: { 292: // Get the calling classloader 293: ClassLoader cl = VMStackWalker.getCallingClassLoader(); 294: if (cl != null && !cl.isAncestorOf(loader)) 295: sm.checkPermission(new RuntimePermission("getClassLoader")); 296: } 297: return loader; 298: } 299: 300: /** 301: * If this is an array, get the Class representing the type of array. 302: * Examples: "[[Ljava.lang.String;" would return "[Ljava.lang.String;", and 303: * calling getComponentType on that would give "java.lang.String". If 304: * this is not an array, returns null. 305: * 306: * @return the array type of this class, or null 307: * @see Array 308: * @since 1.1 309: */ 310: public Class getComponentType() 311: { 312: return VMClass.getComponentType (this); 313: } 314: 315: /** 316: * Get a public constructor declared in this class. If the constructor takes 317: * no argument, an array of zero elements and null are equivalent for the 318: * types argument. A security check may be performed, with 319: * <code>checkMemberAccess(this, Member.PUBLIC)</code> as well as 320: * <code>checkPackageAccess</code> both having to succeed. 321: * 322: * @param types the type of each parameter 323: * @return the constructor 324: * @throws NoSuchMethodException if the constructor does not exist 325: * @throws SecurityException if the security check fails 326: * @see #getConstructors() 327: * @since 1.1 328: */ 329: public Constructor getConstructor(Class[] types) throws NoSuchMethodException 330: { 331: memberAccessCheck(Member.PUBLIC); 332: Constructor[] constructors = getDeclaredConstructors(true); 333: for (int i = 0; i < constructors.length; i++) 334: { 335: Constructor constructor = constructors[i]; 336: if (matchParameters(types, constructor.getParameterTypes())) 337: return constructor; 338: } 339: throw new NoSuchMethodException(); 340: } 341: 342: /** 343: * Get all the public constructors of this class. This returns an array of 344: * length 0 if there are no constructors, including for primitive types, 345: * arrays, and interfaces. It does, however, include the default 346: * constructor if one was supplied by the compiler. A security check may 347: * be performed, with <code>checkMemberAccess(this, Member.PUBLIC)</code> 348: * as well as <code>checkPackageAccess</code> both having to succeed. 349: * 350: * @return all public constructors in this class 351: * @throws SecurityException if the security check fails 352: * @since 1.1 353: */ 354: public Constructor[] getConstructors() 355: { 356: memberAccessCheck(Member.PUBLIC); 357: return getDeclaredConstructors(true); 358: } 359: 360: /** 361: * Get a constructor declared in this class. If the constructor takes no 362: * argument, an array of zero elements and null are equivalent for the 363: * types argument. A security check may be performed, with 364: * <code>checkMemberAccess(this, Member.DECLARED)</code> as well as 365: * <code>checkPackageAccess</code> both having to succeed. 366: * 367: * @param types the type of each parameter 368: * @return the constructor 369: * @throws NoSuchMethodException if the constructor does not exist 370: * @throws SecurityException if the security check fails 371: * @see #getDeclaredConstructors() 372: * @since 1.1 373: */ 374: public Constructor getDeclaredConstructor(Class[] types) 375: throws NoSuchMethodException 376: { 377: memberAccessCheck(Member.DECLARED); 378: Constructor[] constructors = getDeclaredConstructors(false); 379: for (int i = 0; i < constructors.length; i++) 380: { 381: Constructor constructor = constructors[i]; 382: if (matchParameters(types, constructor.getParameterTypes())) 383: return constructor; 384: } 385: throw new NoSuchMethodException(); 386: } 387: 388: /** 389: * Get all the declared member classes and interfaces in this class, but 390: * not those inherited from superclasses. This returns an array of length 391: * 0 if there are no member classes, including for primitive types. A 392: * security check may be performed, with 393: * <code>checkMemberAccess(this, Member.DECLARED)</code> as well as 394: * <code>checkPackageAccess</code> both having to succeed. 395: * 396: * @return all declared member classes in this class 397: * @throws SecurityException if the security check fails 398: * @since 1.1 399: */ 400: public Class[] getDeclaredClasses() 401: { 402: memberAccessCheck(Member.DECLARED); 403: return getDeclaredClasses(false); 404: } 405: 406: Class[] getDeclaredClasses (boolean publicOnly) 407: { 408: return VMClass.getDeclaredClasses (this, publicOnly); 409: } 410: 411: /** 412: * Get all the declared constructors of this class. This returns an array of 413: * length 0 if there are no constructors, including for primitive types, 414: * arrays, and interfaces. It does, however, include the default 415: * constructor if one was supplied by the compiler. A security check may 416: * be performed, with <code>checkMemberAccess(this, Member.DECLARED)</code> 417: * as well as <code>checkPackageAccess</code> both having to succeed. 418: * 419: * @return all constructors in this class 420: * @throws SecurityException if the security check fails 421: * @since 1.1 422: */ 423: public Constructor[] getDeclaredConstructors() 424: { 425: memberAccessCheck(Member.DECLARED); 426: return getDeclaredConstructors(false); 427: } 428: 429: Constructor[] getDeclaredConstructors (boolean publicOnly) 430: { 431: return VMClass.getDeclaredConstructors (this, publicOnly); 432: } 433: 434: /** 435: * Get a field declared in this class, where name is its simple name. The 436: * implicit length field of arrays is not available. A security check may 437: * be performed, with <code>checkMemberAccess(this, Member.DECLARED)</code> 438: * as well as <code>checkPackageAccess</code> both having to succeed. 439: * 440: * @param name the name of the field 441: * @return the field 442: * @throws NoSuchFieldException if the field does not exist 443: * @throws SecurityException if the security check fails 444: * @see #getDeclaredFields() 445: * @since 1.1 446: */ 447: public Field getDeclaredField(String name) throws NoSuchFieldException 448: { 449: memberAccessCheck(Member.DECLARED); 450: Field[] fields = getDeclaredFields(false); 451: for (int i = 0; i < fields.length; i++) 452: { 453: if (fields[i].getName().equals(name)) 454: return fields[i]; 455: } 456: throw new NoSuchFieldException(); 457: } 458: 459: /** 460: * Get all the declared fields in this class, but not those inherited from 461: * superclasses. This returns an array of length 0 if there are no fields, 462: * including for primitive types. This does not return the implicit length 463: * field of arrays. A security check may be performed, with 464: * <code>checkMemberAccess(this, Member.DECLARED)</code> as well as 465: * <code>checkPackageAccess</code> both having to succeed. 466: * 467: * @return all declared fields in this class 468: * @throws SecurityException if the security check fails 469: * @since 1.1 470: */ 471: public Field[] getDeclaredFields() 472: { 473: memberAccessCheck(Member.DECLARED); 474: return getDeclaredFields(false); 475: } 476: 477: Field[] getDeclaredFields (boolean publicOnly) 478: { 479: return VMClass.getDeclaredFields (this, publicOnly); 480: } 481: 482: /** 483: * Get a method declared in this class, where name is its simple name. The 484: * implicit methods of Object are not available from arrays or interfaces. 485: * Constructors (named "<init>" in the class file) and class initializers 486: * (name "<clinit>") are not available. The Virtual Machine allows 487: * multiple methods with the same signature but differing return types; in 488: * such a case the most specific return types are favored, then the final 489: * choice is arbitrary. If the method takes no argument, an array of zero 490: * elements and null are equivalent for the types argument. A security 491: * check may be performed, with 492: * <code>checkMemberAccess(this, Member.DECLARED)</code> as well as 493: * <code>checkPackageAccess</code> both having to succeed. 494: * 495: * @param methodName the name of the method 496: * @param types the type of each parameter 497: * @return the method 498: * @throws NoSuchMethodException if the method does not exist 499: * @throws SecurityException if the security check fails 500: * @see #getDeclaredMethods() 501: * @since 1.1 502: */ 503: public Method getDeclaredMethod(String methodName, Class[] types) 504: throws NoSuchMethodException 505: { 506: memberAccessCheck(Member.DECLARED); 507: Method match = matchMethod(getDeclaredMethods(false), methodName, types); 508: if (match == null) 509: throw new NoSuchMethodException(methodName); 510: return match; 511: } 512: 513: /** 514: * Get all the declared methods in this class, but not those inherited from 515: * superclasses. This returns an array of length 0 if there are no methods, 516: * including for primitive types. This does include the implicit methods of 517: * arrays and interfaces which mirror methods of Object, nor does it 518: * include constructors or the class initialization methods. The Virtual 519: * Machine allows multiple methods with the same signature but differing 520: * return types; all such methods are in the returned array. A security 521: * check may be performed, with 522: * <code>checkMemberAccess(this, Member.DECLARED)</code> as well as 523: * <code>checkPackageAccess</code> both having to succeed. 524: * 525: * @return all declared methods in this class 526: * @throws SecurityException if the security check fails 527: * @since 1.1 528: */ 529: public Method[] getDeclaredMethods() 530: { 531: memberAccessCheck(Member.DECLARED); 532: return getDeclaredMethods(false); 533: } 534: 535: Method[] getDeclaredMethods (boolean publicOnly) 536: { 537: return VMClass.getDeclaredMethods (this, publicOnly); 538: } 539: 540: /** 541: * If this is a nested or inner class, return the class that declared it. 542: * If not, return null. 543: * 544: * @return the declaring class of this class 545: * @since 1.1 546: */ 547: public Class getDeclaringClass() 548: { 549: return VMClass.getDeclaringClass (this); 550: } 551: 552: /** 553: * Get a public field declared or inherited in this class, where name is 554: * its simple name. If the class contains multiple accessible fields by 555: * that name, an arbitrary one is returned. The implicit length field of 556: * arrays is not available. A security check may be performed, with 557: * <code>checkMemberAccess(this, Member.PUBLIC)</code> as well as 558: * <code>checkPackageAccess</code> both having to succeed. 559: * 560: * @param fieldName the name of the field 561: * @return the field 562: * @throws NoSuchFieldException if the field does not exist 563: * @throws SecurityException if the security check fails 564: * @see #getFields() 565: * @since 1.1 566: */ 567: public Field getField(String fieldName) 568: throws NoSuchFieldException 569: { 570: memberAccessCheck(Member.PUBLIC); 571: Field field = internalGetField(fieldName); 572: if (field == null) 573: throw new NoSuchFieldException(fieldName); 574: return field; 575: } 576: 577: /** 578: * Get all the public fields declared in this class or inherited from 579: * superclasses. This returns an array of length 0 if there are no fields, 580: * including for primitive types. This does not return the implicit length 581: * field of arrays. A security check may be performed, with 582: * <code>checkMemberAccess(this, Member.PUBLIC)</code> as well as 583: * <code>checkPackageAccess</code> both having to succeed. 584: * 585: * @return all public fields in this class 586: * @throws SecurityException if the security check fails 587: * @since 1.1 588: */ 589: public Field[] getFields() 590: { 591: memberAccessCheck(Member.PUBLIC); 592: return internalGetFields(); 593: } 594: 595: /** 596: * Like <code>getFields()</code> but without the security checks. 597: */ 598: private Field[] internalGetFields() 599: { 600: HashSet set = new HashSet(); 601: set.addAll(Arrays.asList(getDeclaredFields(true))); 602: Class[] interfaces = getInterfaces(); 603: for (int i = 0; i < interfaces.length; i++) 604: set.addAll(Arrays.asList(interfaces[i].internalGetFields())); 605: Class superClass = getSuperclass(); 606: if (superClass != null) 607: set.addAll(Arrays.asList(superClass.internalGetFields())); 608: return (Field[])set.toArray(new Field[set.size()]); 609: } 610: 611: /** 612: * Returns the <code>Package</code> in which this class is defined 613: * Returns null when this information is not available from the 614: * classloader of this class. 615: * 616: * @return the package for this class, if it is available 617: * @since 1.2 618: */ 619: public Package getPackage() 620: { 621: ClassLoader cl = getClassLoader(); 622: if (cl != null) 623: return cl.getPackage(getPackagePortion(getName())); 624: else 625: return VMClassLoader.getPackage(getPackagePortion(getName())); 626: } 627: 628: /** 629: * Get the interfaces this class <em>directly</em> implements, in the 630: * order that they were declared. This returns an empty array, not null, 631: * for Object, primitives, void, and classes or interfaces with no direct 632: * superinterface. Array types return Cloneable and Serializable. 633: * 634: * @return the interfaces this class directly implements 635: */ 636: public Class[] getInterfaces() 637: { 638: return VMClass.getInterfaces (this); 639: } 640: 641: private static final class MethodKey 642: { 643: private String name; 644: private Class[] params; 645: private Class returnType; 646: private int hash; 647: 648: MethodKey(Method m) 649: { 650: name = m.getName(); 651: params = m.getParameterTypes(); 652: returnType = m.getReturnType(); 653: hash = name.hashCode() ^ returnType.hashCode(); 654: for(int i = 0; i < params.length; i++) 655: { 656: hash ^= params[i].hashCode(); 657: } 658: } 659: 660: public boolean equals(Object o) 661: { 662: if (o instanceof MethodKey) 663: { 664: MethodKey m = (MethodKey) o; 665: if (m.name.equals(name) && m.params.length == params.length 666: && m.returnType == returnType) 667: { 668: for (int i = 0; i < params.length; i++) 669: { 670: if (m.params[i] != params[i]) 671: return false; 672: } 673: return true; 674: } 675: } 676: return false; 677: } 678: 679: public int hashCode() 680: { 681: return hash; 682: } 683: } 684: 685: /** 686: * Get a public method declared or inherited in this class, where name is 687: * its simple name. The implicit methods of Object are not available from 688: * interfaces. Constructors (named "<init>" in the class file) and class 689: * initializers (name "<clinit>") are not available. The Virtual 690: * Machine allows multiple methods with the same signature but differing 691: * return types, and the class can inherit multiple methods of the same 692: * return type; in such a case the most specific return types are favored, 693: * then the final choice is arbitrary. If the method takes no argument, an 694: * array of zero elements and null are equivalent for the types argument. 695: * A security check may be performed, with 696: * <code>checkMemberAccess(this, Member.PUBLIC)</code> as well as 697: * <code>checkPackageAccess</code> both having to succeed. 698: * 699: * @param methodName the name of the method 700: * @param types the type of each parameter 701: * @return the method 702: * @throws NoSuchMethodException if the method does not exist 703: * @throws SecurityException if the security check fails 704: * @see #getMethods() 705: * @since 1.1 706: */ 707: public Method getMethod(String methodName, Class[] types) 708: throws NoSuchMethodException 709: { 710: memberAccessCheck(Member.PUBLIC); 711: Method method = internalGetMethod(methodName, types); 712: if (method == null) 713: throw new NoSuchMethodException(methodName); 714: return method; 715: } 716: 717: /** 718: * Like <code>getMethod(String,Class[])</code> but without the security 719: * checks and returns null instead of throwing NoSuchMethodException. 720: */ 721: private Method internalGetMethod(String methodName, Class[] args) 722: { 723: Method match = matchMethod(getDeclaredMethods(true), methodName, args); 724: if (match != null) 725: return match; 726: Class superClass = getSuperclass(); 727: if (superClass != null) 728: { 729: match = superClass.internalGetMethod(methodName, args); 730: if(match != null) 731: return match; 732: } 733: Class[] interfaces = getInterfaces(); 734: for (int i = 0; i < interfaces.length; i++) 735: { 736: match = interfaces[i].internalGetMethod(methodName, args); 737: if (match != null) 738: return match; 739: } 740: return null; 741: } 742: 743: /** 744: * Find the best matching method in <code>list</code> according to 745: * the definition of ``best matching'' used by <code>getMethod()</code> 746: * 747: * <p> 748: * Returns the method if any, otherwise <code>null</code>. 749: * 750: * @param list List of methods to search 751: * @param name Name of method 752: * @param args Method parameter types 753: * @see #getMethod(String, Class[]) 754: */ 755: private static Method matchMethod(Method[] list, String name, Class[] args) 756: { 757: Method match = null; 758: for (int i = 0; i < list.length; i++) 759: { 760: Method method = list[i]; 761: if (!method.getName().equals(name)) 762: continue; 763: if (!matchParameters(args, method.getParameterTypes())) 764: continue; 765: if (match == null 766: || match.getReturnType().isAssignableFrom(method.getReturnType())) 767: match = method; 768: } 769: return match; 770: } 771: 772: /** 773: * Check for an exact match between parameter type lists. 774: * Either list may be <code>null</code> to mean a list of 775: * length zero. 776: */ 777: private static boolean matchParameters(Class[] types1, Class[] types2) 778: { 779: if (types1 == null) 780: return types2 == null || types2.length == 0; 781: if (types2 == null) 782: return types1 == null || types1.length == 0; 783: if (types1.length != types2.length) 784: return false; 785: for (int i = 0; i < types1.length; i++) 786: { 787: if (types1[i] != types2[i]) 788: return false; 789: } 790: return true; 791: } 792: 793: /** 794: * Get all the public methods declared in this class or inherited from 795: * superclasses. This returns an array of length 0 if there are no methods, 796: * including for primitive types. This does not include the implicit 797: * methods of interfaces which mirror methods of Object, nor does it 798: * include constructors or the class initialization methods. The Virtual 799: * Machine allows multiple methods with the same signature but differing 800: * return types; all such methods are in the returned array. A security 801: * check may be performed, with 802: * <code>checkMemberAccess(this, Member.PUBLIC)</code> as well as 803: * <code>checkPackageAccess</code> both having to succeed. 804: * 805: * @return all public methods in this class 806: * @throws SecurityException if the security check fails 807: * @since 1.1 808: */ 809: public Method[] getMethods() 810: { 811: memberAccessCheck(Member.PUBLIC); 812: // NOTE the API docs claim that no methods are returned for arrays, 813: // but Sun's implementation *does* return the public methods of Object 814: // (as would be expected), so we follow their implementation instead 815: // of their documentation. 816: return internalGetMethods(); 817: } 818: 819: /** 820: * Like <code>getMethods()</code> but without the security checks. 821: */ 822: private Method[] internalGetMethods() 823: { 824: HashMap map = new HashMap(); 825: Method[] methods; 826: Class[] interfaces = getInterfaces(); 827: for(int i = 0; i < interfaces.length; i++) 828: { 829: methods = interfaces[i].internalGetMethods(); 830: for(int j = 0; j < methods.length; j++) 831: { 832: map.put(new MethodKey(methods[j]), methods[j]); 833: } 834: } 835: Class superClass = getSuperclass(); 836: if(superClass != null) 837: { 838: methods = superClass.internalGetMethods(); 839: for(int i = 0; i < methods.length; i++) 840: { 841: map.put(new MethodKey(methods[i]), methods[i]); 842: } 843: } 844: methods = getDeclaredMethods(true); 845: for(int i = 0; i < methods.length; i++) 846: { 847: map.put(new MethodKey(methods[i]), methods[i]); 848: } 849: return (Method[])map.values().toArray(new Method[map.size()]); 850: } 851: 852: /** 853: * Get the modifiers of this class. These can be decoded using Modifier, 854: * and is limited to one of public, protected, or private, and any of 855: * final, static, abstract, or interface. An array class has the same 856: * public, protected, or private modifier as its component type, and is 857: * marked final but not an interface. Primitive types and void are marked 858: * public and final, but not an interface. 859: * 860: * @return the modifiers of this class 861: * @see Modifier 862: * @since 1.1 863: */ 864: public int getModifiers() 865: { 866: int mod = VMClass.getModifiers (this, false); 867: return (mod & (Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE | 868: Modifier.FINAL | Modifier.STATIC | Modifier.ABSTRACT | 869: Modifier.INTERFACE)); 870: } 871: 872: /** 873: * Get the name of this class, separated by dots for package separators. 874: * If the class represents a primitive type, or void, then the 875: * name of the type as it appears in the Java programming language 876: * is returned. For instance, <code>Byte.TYPE.getName()</code> 877: * returns "byte". 878: * 879: * Arrays are specially encoded as shown on this table. 880: * <pre> 881: * array type [<em>element type</em> 882: * (note that the element type is encoded per 883: * this table) 884: * boolean Z 885: * byte B 886: * char C 887: * short S 888: * int I 889: * long J 890: * float F 891: * double D 892: * void V 893: * class or interface, alone: <dotted name> 894: * class or interface, as element type: L<dotted name>; 895: * </pre> 896: * 897: * @return the name of this class 898: */ 899: public String getName() 900: { 901: return VMClass.getName (this); 902: } 903: 904: /** 905: * Get a resource URL using this class's package using the 906: * getClassLoader().getResource() method. If this class was loaded using 907: * the system classloader, ClassLoader.getSystemResource() is used instead. 908: * 909: * <p>If the name you supply is absolute (it starts with a <code>/</code>), 910: * then the leading <code>/</code> is removed and it is passed on to 911: * getResource(). If it is relative, the package name is prepended, and 912: * <code>.</code>'s are replaced with <code>/</code>. 913: * 914: * <p>The URL returned is system- and classloader-dependent, and could 915: * change across implementations. 916: * 917: * @param resourceName the name of the resource, generally a path 918: * @return the URL to the resource 919: * @throws NullPointerException if name is null 920: * @since 1.1 921: */ 922: public URL getResource(String resourceName) 923: { 924: String name = resourcePath(resourceName); 925: ClassLoader loader = getClassLoader(); 926: if (loader == null) 927: return ClassLoader.getSystemResource(name); 928: return loader.getResource(name); 929: } 930: 931: /** 932: * Get a resource using this class's package using the 933: * getClassLoader().getResourceAsStream() method. If this class was loaded 934: * using the system classloader, ClassLoader.getSystemResource() is used 935: * instead. 936: * 937: * <p>If the name you supply is absolute (it starts with a <code>/</code>), 938: * then the leading <code>/</code> is removed and it is passed on to 939: * getResource(). If it is relative, the package name is prepended, and 940: * <code>.</code>'s are replaced with <code>/</code>. 941: * 942: * <p>The URL returned is system- and classloader-dependent, and could 943: * change across implementations. 944: * 945: * @param resourceName the name of the resource, generally a path 946: * @return an InputStream with the contents of the resource in it, or null 947: * @throws NullPointerException if name is null 948: * @since 1.1 949: */ 950: public InputStream getResourceAsStream(String resourceName) 951: { 952: String name = resourcePath(resourceName); 953: ClassLoader loader = getClassLoader(); 954: if (loader == null) 955: return ClassLoader.getSystemResourceAsStream(name); 956: return loader.getResourceAsStream(name); 957: } 958: 959: private String resourcePath(String resourceName) 960: { 961: if (resourceName.length() > 0) 962: { 963: if (resourceName.charAt(0) != '/') 964: { 965: String pkg = getPackagePortion(getName()); 966: if (pkg.length() > 0) 967: resourceName = pkg.replace('.','/') + '/' + resourceName; 968: } 969: else 970: { 971: resourceName = resourceName.substring(1); 972: } 973: } 974: return resourceName; 975: } 976: 977: /** 978: * Get the signers of this class. This returns null if there are no signers, 979: * such as for primitive types or void. 980: * 981: * @return the signers of this class 982: * @since 1.1 983: */ 984: public Object[] getSigners() 985: { 986: return signers == null ? null : (Object[]) signers.clone (); 987: } 988: 989: /** 990: * Set the signers of this class. 991: * 992: * @param signers the signers of this class 993: */ 994: void setSigners(Object[] signers) 995: { 996: this.signers = signers; 997: } 998: 999: /** 1000: * Get the direct superclass of this class. If this is an interface, 1001: * Object, a primitive type, or void, it will return null. If this is an 1002: * array type, it will return Object. 1003: * 1004: * @return the direct superclass of this class 1005: */ 1006: public Class getSuperclass() 1007: { 1008: return VMClass.getSuperclass (this); 1009: } 1010: 1011: /** 1012: * Return whether this class is an array type. 1013: * 1014: * @return whether this class is an array type 1015: * @since 1.1 1016: */ 1017: public boolean isArray() 1018: { 1019: return VMClass.isArray (this); 1020: } 1021: 1022: /** 1023: * Discover whether an instance of the Class parameter would be an 1024: * instance of this Class as well. Think of doing 1025: * <code>isInstance(c.newInstance())</code> or even 1026: * <code>c.newInstance() instanceof (this class)</code>. While this 1027: * checks widening conversions for objects, it must be exact for primitive 1028: * types. 1029: * 1030: * @param c the class to check 1031: * @return whether an instance of c would be an instance of this class 1032: * as well 1033: * @throws NullPointerException if c is null 1034: * @since 1.1 1035: */ 1036: public boolean isAssignableFrom(Class c) 1037: { 1038: return VMClass.isAssignableFrom (this, c); 1039: } 1040: 1041: /** 1042: * Discover whether an Object is an instance of this Class. Think of it 1043: * as almost like <code>o instanceof (this class)</code>. 1044: * 1045: * @param o the Object to check 1046: * @return whether o is an instance of this class 1047: * @since 1.1 1048: */ 1049: public boolean isInstance(Object o) 1050: { 1051: return VMClass.isInstance (this, o); 1052: } 1053: 1054: /** 1055: * Check whether this class is an interface or not. Array types are not 1056: * interfaces. 1057: * 1058: * @return whether this class is an interface or not 1059: */ 1060: public boolean isInterface() 1061: { 1062: return VMClass.isInterface (this); 1063: } 1064: 1065: /** 1066: * Return whether this class is a primitive type. A primitive type class 1067: * is a class representing a kind of "placeholder" for the various 1068: * primitive types, or void. You can access the various primitive type 1069: * classes through java.lang.Boolean.TYPE, java.lang.Integer.TYPE, etc., 1070: * or through boolean.class, int.class, etc. 1071: * 1072: * @return whether this class is a primitive type 1073: * @see Boolean#TYPE 1074: * @see Byte#TYPE 1075: * @see Character#TYPE 1076: * @see Short#TYPE 1077: * @see Integer#TYPE 1078: * @see Long#TYPE 1079: * @see Float#TYPE 1080: * @see Double#TYPE 1081: * @see Void#TYPE 1082: * @since 1.1 1083: */ 1084: public boolean isPrimitive() 1085: { 1086: return VMClass.isPrimitive (this); 1087: } 1088: 1089: /** 1090: * Get a new instance of this class by calling the no-argument constructor. 1091: * The class is initialized if it has not been already. A security check 1092: * may be performed, with <code>checkMemberAccess(this, Member.PUBLIC)</code> 1093: * as well as <code>checkPackageAccess</code> both having to succeed. 1094: * 1095: * @return a new instance of this class 1096: * @throws InstantiationException if there is not a no-arg constructor 1097: * for this class, including interfaces, abstract classes, arrays, 1098: * primitive types, and void; or if an exception occurred during 1099: * the constructor 1100: * @throws IllegalAccessException if you are not allowed to access the 1101: * no-arg constructor because of scoping reasons 1102: * @throws SecurityException if the security check fails 1103: * @throws ExceptionInInitializerError if class initialization caused by 1104: * this call fails with an exception 1105: */ 1106: public Object newInstance() 1107: throws InstantiationException, IllegalAccessException 1108: { 1109: memberAccessCheck(Member.PUBLIC); 1110: Constructor constructor; 1111: synchronized(this) 1112: { 1113: constructor = this.constructor; 1114: } 1115: if (constructor == null) 1116: { 1117: Constructor[] constructors = getDeclaredConstructors(false); 1118: for (int i = 0; i < constructors.length; i++) 1119: { 1120: if (constructors[i].getParameterTypes().length == 0) 1121: { 1122: constructor = constructors[i]; 1123: break; 1124: } 1125: } 1126: if (constructor == null) 1127: throw new InstantiationException(getName()); 1128: if (!Modifier.isPublic(constructor.getModifiers()) 1129: || !Modifier.isPublic(VMClass.getModifiers(this, true))) 1130: { 1131: final Constructor finalConstructor = constructor; 1132: AccessController.doPrivileged(new PrivilegedAction() 1133: { 1134: public Object run() 1135: { 1136: finalConstructor.setAccessible(true); 1137: return null; 1138: } 1139: }); 1140: } 1141: synchronized(this) 1142: { 1143: if (this.constructor == null) 1144: this.constructor = constructor; 1145: } 1146: } 1147: int modifiers = constructor.getModifiers(); 1148: if (!Modifier.isPublic(modifiers) 1149: || !Modifier.isPublic(VMClass.getModifiers(this, true))) 1150: { 1151: Class caller = VMStackWalker.getCallingClass(); 1152: if (caller != null && 1153: caller != this && 1154: (Modifier.isPrivate(modifiers) 1155: || getClassLoader() != caller.getClassLoader() 1156: || !getPackagePortion(getName()) 1157: .equals(getPackagePortion(caller.getName())))) 1158: throw new IllegalAccessException(getName() 1159: + " has an inaccessible constructor"); 1160: } 1161: try 1162: { 1163: return constructor.newInstance(null); 1164: } 1165: catch (InvocationTargetException e) 1166: { 1167: VMClass.throwException(e.getTargetException()); 1168: throw (InternalError) new InternalError 1169: ("VMClass.throwException returned").initCause(e); 1170: } 1171: } 1172: 1173: /** 1174: * Returns the protection domain of this class. If the classloader did not 1175: * record the protection domain when creating this class the unknown 1176: * protection domain is returned which has a <code>null</code> code source 1177: * and all permissions. A security check may be performed, with 1178: * <code>RuntimePermission("getProtectionDomain")</code>. 1179: * 1180: * @return the protection domain 1181: * @throws SecurityException if the security manager exists and the caller 1182: * does not have <code>RuntimePermission("getProtectionDomain")</code>. 1183: * @see RuntimePermission 1184: * @since 1.2 1185: */ 1186: public ProtectionDomain getProtectionDomain() 1187: { 1188: SecurityManager sm = SecurityManager.current; 1189: if (sm != null) 1190: sm.checkPermission(new RuntimePermission("getProtectionDomain")); 1191: 1192: return pd == null ? StaticData.unknownProtectionDomain : pd; 1193: } 1194: 1195: /** 1196: * Return the human-readable form of this Object. For an object, this 1197: * is either "interface " or "class " followed by <code>getName()</code>, 1198: * for primitive types and void it is just <code>getName()</code>. 1199: * 1200: * @return the human-readable form of this Object 1201: */ 1202: public String toString() 1203: { 1204: if (isPrimitive()) 1205: return getName(); 1206: return (isInterface() ? "interface " : "class ") + getName(); 1207: } 1208: 1209: /** 1210: * Returns the desired assertion status of this class, if it were to be 1211: * initialized at this moment. The class assertion status, if set, is 1212: * returned; the backup is the default package status; then if there is 1213: * a class loader, that default is returned; and finally the system default 1214: * is returned. This method seldom needs calling in user code, but exists 1215: * for compilers to implement the assert statement. Note that there is no 1216: * guarantee that the result of this method matches the class's actual 1217: * assertion status. 1218: * 1219: * @return the desired assertion status 1220: * @see ClassLoader#setClassAssertionStatus(String, boolean) 1221: * @see ClassLoader#setPackageAssertionStatus(String, boolean) 1222: * @see ClassLoader#setDefaultAssertionStatus(boolean) 1223: * @since 1.4 1224: */ 1225: public boolean desiredAssertionStatus() 1226: { 1227: ClassLoader c = getClassLoader(); 1228: Object status; 1229: if (c == null) 1230: return VMClassLoader.defaultAssertionStatus(); 1231: if (c.classAssertionStatus != null) 1232: synchronized (c) 1233: { 1234: status = c.classAssertionStatus.get(getName()); 1235: if (status != null) 1236: return status.equals(Boolean.TRUE); 1237: } 1238: else 1239: { 1240: status = ClassLoader.StaticData. 1241: systemClassAssertionStatus.get(getName()); 1242: if (status != null) 1243: return status.equals(Boolean.TRUE); 1244: } 1245: if (c.packageAssertionStatus != null) 1246: synchronized (c) 1247: { 1248: String name = getPackagePortion(getName()); 1249: if ("".equals(name)) 1250: status = c.packageAssertionStatus.get(null); 1251: else 1252: do 1253: { 1254: status = c.packageAssertionStatus.get(name); 1255: name = getPackagePortion(name); 1256: } 1257: while (! "".equals(name) && status == null); 1258: if (status != null) 1259: return status.equals(Boolean.TRUE); 1260: } 1261: else 1262: { 1263: String name = getPackagePortion(getName()); 1264: if ("".equals(name)) 1265: status = ClassLoader.StaticData. 1266: systemPackageAssertionStatus.get(null); 1267: else 1268: do 1269: { 1270: status = ClassLoader.StaticData. 1271: systemPackageAssertionStatus.get(name); 1272: name = getPackagePortion(name); 1273: } 1274: while (! "".equals(name) && status == null); 1275: if (status != null) 1276: return status.equals(Boolean.TRUE); 1277: } 1278: return c.defaultAssertionStatus; 1279: } 1280: 1281: /** 1282: * <p> 1283: * Casts this class to represent a subclass of the specified class. 1284: * This method is useful for `narrowing' the type of a class so that 1285: * the class object, and instances of that class, can match the contract 1286: * of a more restrictive method. For example, if this class has the 1287: * static type of <code>Class<Object></code>, and a dynamic type of 1288: * <code>Class<Rectangle></code>, then, assuming <code>Shape</code> is 1289: * a superclass of <code>Rectangle</code>, this method can be used on 1290: * this class with the parameter, <code>Class<Shape></code>, to retain 1291: * the same instance but with the type 1292: * <code>Class<? extends Shape></code>. 1293: * </p> 1294: * <p> 1295: * If this class can be converted to an instance which is parameterised 1296: * over a subtype of the supplied type, <code>U</code>, then this method 1297: * returns an appropriately cast reference to this object. Otherwise, 1298: * a <code>ClassCastException</code> is thrown. 1299: * </p> 1300: * 1301: * @param klass the class object, the parameterized type (<code>U</code>) of 1302: * which should be a superclass of the parameterized type of 1303: * this instance. 1304: * @return a reference to this object, appropriately cast. 1305: * @throws ClassCastException if this class can not be converted to one 1306: * which represents a subclass of the specified 1307: * type, <code>U</code>. 1308: * @since 1.5 1309: */ 1310: /* FIXME[GENERICS]: Should be <U> Class<? extends U> asSubClass(Class<U> klass */ 1311: public Class asSubclass(Class klass) 1312: { 1313: if (! klass.isAssignableFrom(this)) 1314: throw new ClassCastException(); 1315: return this; /* FIXME[GENERICS]: Should cast to Class<? extends U> */ 1316: } 1317: 1318: /** 1319: * Returns the specified object, cast to this <code>Class</code>' type. 1320: * 1321: * @param obj the object to cast 1322: * @throws ClassCastException if obj is not an instance of this class 1323: * @since 1.5 1324: */ 1325: /* FIXME[GENERICS]: Should be T cast(Object obj) */ 1326: public Object cast(Object obj) 1327: { 1328: if (obj != null && ! isInstance(obj)) 1329: throw new ClassCastException(); 1330: return obj; /* FIXME[GENERICS]: Should be cast to T */ 1331: } 1332: 1333: /** 1334: * Like <code>getField(String)</code> but without the security checks and 1335: * returns null instead of throwing NoSuchFieldException. 1336: */ 1337: private Field internalGetField(String name) 1338: { 1339: Field[] fields = getDeclaredFields(true); 1340: for (int i = 0; i < fields.length; i++) 1341: { 1342: Field field = fields[i]; 1343: if (field.getName().equals(name)) 1344: return field; 1345: } 1346: Class[] interfaces = getInterfaces(); 1347: for (int i = 0; i < interfaces.length; i++) 1348: { 1349: Field field = interfaces[i].internalGetField(name); 1350: if(field != null) 1351: return field; 1352: } 1353: Class superClass = getSuperclass(); 1354: if (superClass != null) 1355: return superClass.internalGetField(name); 1356: return null; 1357: } 1358: 1359: /** 1360: * Strip the last portion of the name (after the last dot). 1361: * 1362: * @param name the name to get package of 1363: * @return the package name, or "" if no package 1364: */ 1365: private static String getPackagePortion(String name) 1366: { 1367: int lastInd = name.lastIndexOf('.'); 1368: if (lastInd == -1) 1369: return ""; 1370: return name.substring(0, lastInd); 1371: } 1372: 1373: /** 1374: * Perform security checks common to all of the methods that 1375: * get members of this Class. 1376: */ 1377: private void memberAccessCheck(int which) 1378: { 1379: SecurityManager sm = SecurityManager.current; 1380: if (sm != null) 1381: { 1382: sm.checkMemberAccess(this, which); 1383: Package pkg = getPackage(); 1384: if (pkg != null) 1385: sm.checkPackageAccess(pkg.getName()); 1386: } 1387: } 1388: 1389: /** 1390: * Returns the enumeration constants of this class, or 1391: * null if this class is not an <code>Enum</code>. 1392: * 1393: * @return an array of <code>Enum</code> constants 1394: * associated with this class, or null if this 1395: * class is not an <code>enum</code>. 1396: * @since 1.5 1397: */ 1398: /* FIXME[GENERICS]: T[] getEnumConstants() */ 1399: public Object[] getEnumConstants() 1400: { 1401: if (isEnum()) 1402: { 1403: try 1404: { 1405: return (Object[]) 1406: getMethod("values", new Class[0]).invoke(null, new Object[0]); 1407: } 1408: catch (NoSuchMethodException exception) 1409: { 1410: throw new Error("Enum lacks values() method"); 1411: } 1412: catch (IllegalAccessException exception) 1413: { 1414: throw new Error("Unable to access Enum class"); 1415: } 1416: catch (InvocationTargetException exception) 1417: { 1418: throw new 1419: RuntimeException("The values method threw an exception", 1420: exception); 1421: } 1422: } 1423: else 1424: { 1425: return null; 1426: } 1427: } 1428: 1429: /** 1430: * Returns true if this class is an <code>Enum</code>. 1431: * 1432: * @return true if this is an enumeration class. 1433: * @since 1.5 1434: */ 1435: public boolean isEnum() 1436: { 1437: int mod = VMClass.getModifiers (this, true); 1438: return (mod & ENUM) != 0; 1439: } 1440: 1441: /** 1442: * Returns true if this class is a synthetic class, generated by 1443: * the compiler. 1444: * 1445: * @return true if this is a synthetic class. 1446: * @since 1.5 1447: */ 1448: public boolean isSynthetic() 1449: { 1450: int mod = VMClass.getModifiers (this, true); 1451: return (mod & SYNTHETIC) != 0; 1452: } 1453: 1454: /** 1455: * Returns true if this class is an <code>Annotation</code>. 1456: * 1457: * @return true if this is an annotation class. 1458: * @since 1.5 1459: */ 1460: public boolean isAnnotation() 1461: { 1462: int mod = VMClass.getModifiers (this, true); 1463: return (mod & ANNOTATION) != 0; 1464: } 1465: 1466: /** 1467: * Returns the simple name for this class, as used in the source 1468: * code. For normal classes, this is the content returned by 1469: * <code>getName()</code> which follows the last ".". Anonymous 1470: * classes have no name, and so the result of calling this method is 1471: * "". The simple name of an array consists of the simple name of 1472: * its component type, followed by "[]". Thus, an array with the 1473: * component type of an anonymous class has a simple name of simply 1474: * "[]". 1475: * 1476: * @return the simple name for this class. 1477: * @since 1.5 1478: */ 1479: public String getSimpleName() 1480: { 1481: return VMClass.getSimpleName(this); 1482: } 1483: 1484: /** 1485: * Returns this class' annotation for the specified annotation type, 1486: * or <code>null</code> if no such annotation exists. 1487: * 1488: * @param annotationClass the type of annotation to look for. 1489: * @return this class' annotation for the specified type, or 1490: * <code>null</code> if no such annotation exists. 1491: * @since 1.5 1492: */ 1493: /* FIXME[GENERICS]: <T extends Annotation> T getAnnotation(Class <T>) */ 1494: public Annotation getAnnotation(Class annotationClass) 1495: { 1496: Annotation foundAnnotation = null; 1497: Annotation[] annotations = getAnnotations(); 1498: for (int i = 0; i < annotations.length; i++) 1499: if (annotations[i].annotationType() == annotationClass) 1500: foundAnnotation = annotations[i]; 1501: return foundAnnotation; 1502: } 1503: 1504: /** 1505: * Returns all annotations associated with this class. If there are 1506: * no annotations associated with this class, then a zero-length array 1507: * will be returned. The returned array may be modified by the client 1508: * code, but this will have no effect on the annotation content of this 1509: * class, and hence no effect on the return value of this method for 1510: * future callers. 1511: * 1512: * @return this class' annotations. 1513: * @since 1.5 1514: */ 1515: public Annotation[] getAnnotations() 1516: { 1517: HashSet set = new HashSet(); 1518: set.addAll(Arrays.asList(getDeclaredAnnotations())); 1519: Class[] interfaces = getInterfaces(); 1520: for (int i = 0; i < interfaces.length; i++) 1521: set.addAll(Arrays.asList(interfaces[i].getAnnotations())); 1522: Class superClass = getSuperclass(); 1523: if (superClass != null) 1524: set.addAll(Arrays.asList(superClass.getAnnotations())); 1525: return (Annotation[]) set.toArray(new Annotation[set.size()]); 1526: } 1527: 1528: /** 1529: * <p> 1530: * Returns the canonical name of this class, as defined by section 1531: * 6.7 of the Java language specification. Each package, top-level class, 1532: * top-level interface and primitive type has a canonical name. A member 1533: * class has a canonical name, if its parent class has one. Likewise, 1534: * an array type has a canonical name, if its component type does. 1535: * Local or anonymous classes do not have canonical names. 1536: * </p> 1537: * <p> 1538: * The canonical name for top-level classes, top-level interfaces and 1539: * primitive types is always the same as the fully-qualified name. 1540: * For array types, the canonical name is the canonical name of its 1541: * component type with `[]' appended. 1542: * </p> 1543: * <p> 1544: * The canonical name of a member class always refers to the place where 1545: * the class was defined, and is composed of the canonical name of the 1546: * defining class and the simple name of the member class, joined by `.'. 1547: * For example, if a <code>Person</code> class has an inner class, 1548: * <code>M</code>, then both its fully-qualified name and canonical name 1549: * is <code>Person.M</code>. A subclass, <code>Staff</code>, of 1550: * <code>Person</code> refers to the same inner class by the fully-qualified 1551: * name of <code>Staff.M</code>, but its canonical name is still 1552: * <code>Person.M</code>. 1553: * </p> 1554: * <p> 1555: * Where no canonical name is present, <code>null</code> is returned. 1556: * </p> 1557: * 1558: * @return the canonical name of the class, or <code>null</code> if the 1559: * class doesn't have a canonical name. 1560: * @since 1.5 1561: */ 1562: public String getCanonicalName() 1563: { 1564: return VMClass.getCanonicalName(this); 1565: } 1566: 1567: /** 1568: * Returns all annotations directly defined by this class. If there are 1569: * no annotations associated with this class, then a zero-length array 1570: * will be returned. The returned array may be modified by the client 1571: * code, but this will have no effect on the annotation content of this 1572: * class, and hence no effect on the return value of this method for 1573: * future callers. 1574: * 1575: * @return the annotations directly defined by this class. 1576: * @since 1.5 1577: */ 1578: public Annotation[] getDeclaredAnnotations() 1579: { 1580: return VMClass.getDeclaredAnnotations(this); 1581: } 1582: 1583: /** 1584: * Returns the class which immediately encloses this class. If this class 1585: * is a top-level class, this method returns <code>null</code>. 1586: * 1587: * @return the immediate enclosing class, or <code>null</code> if this is 1588: * a top-level class. 1589: * @since 1.5 1590: */ 1591: /* FIXME[GENERICS]: Should return Class<?> */ 1592: public Class getEnclosingClass() 1593: { 1594: return VMClass.getEnclosingClass(this); 1595: } 1596: 1597: /** 1598: * Returns the constructor which immediately encloses this class. If 1599: * this class is a top-level class, or a local or anonymous class 1600: * immediately enclosed by a type definition, instance initializer 1601: * or static initializer, then <code>null</code> is returned. 1602: * 1603: * @return the immediate enclosing constructor if this class is 1604: * declared within a constructor. Otherwise, <code>null</code> 1605: * is returned. 1606: * @since 1.5 1607: */ 1608: /* FIXME[GENERICS]: Should return Constructor<?> */ 1609: public Constructor getEnclosingConstructor() 1610: { 1611: return VMClass.getEnclosingConstructor(this); 1612: } 1613: 1614: /** 1615: * Returns the method which immediately encloses this class. If 1616: * this class is a top-level class, or a local or anonymous class 1617: * immediately enclosed by a type definition, instance initializer 1618: * or static initializer, then <code>null</code> is returned. 1619: * 1620: * @return the immediate enclosing method if this class is 1621: * declared within a method. Otherwise, <code>null</code> 1622: * is returned. 1623: * @since 1.5 1624: */ 1625: public Method getEnclosingMethod() 1626: { 1627: return VMClass.getEnclosingMethod(this); 1628: } 1629: 1630: /** 1631: * <p> 1632: * Returns an array of <code>Type</code> objects which represent the 1633: * interfaces directly implemented by this class or extended by this 1634: * interface. 1635: * </p> 1636: * <p> 1637: * If one of the superinterfaces is a parameterized type, then the 1638: * object returned for this interface reflects the actual type 1639: * parameters used in the source code. Type parameters are created 1640: * using the semantics specified by the <code>ParameterizedType</code> 1641: * interface, and only if an instance has not already been created. 1642: * </p> 1643: * <p> 1644: * The order of the interfaces in the array matches the order in which 1645: * the interfaces are declared. For classes which represent an array, 1646: * an array of two interfaces, <code>Cloneable</code> and 1647: * <code>Serializable</code>, is always returned, with the objects in 1648: * that order. A class representing a primitive type or void always 1649: * returns an array of zero size. 1650: * </p> 1651: * 1652: * @return an array of interfaces implemented or extended by this class. 1653: * @throws GenericSignatureFormatError if the generic signature of one 1654: * of the interfaces does not comply with that specified by the Java 1655: * Virtual Machine specification, 3rd edition. 1656: * @throws TypeNotPresentException if any of the superinterfaces refers 1657: * to a non-existant type. 1658: * @throws MalformedParameterizedTypeException if any of the interfaces 1659: * refer to a parameterized type that can not be instantiated for 1660: * some reason. 1661: * @since 1.5 1662: * @see java.lang.reflect.ParameterizedType 1663: */ 1664: public Type[] getGenericInterfaces() 1665: { 1666: if (isPrimitive()) 1667: return new Type[0]; 1668: 1669: String sig = VMClass.getClassSignature(this); 1670: if (sig == null) 1671: return getInterfaces(); 1672: 1673: ClassSignatureParser p = new ClassSignatureParser(this, sig); 1674: return p.getInterfaceTypes(); 1675: } 1676: 1677: /** 1678: * <p> 1679: * Returns a <code>Type</code> object representing the direct superclass, 1680: * whether class, interface, primitive type or void, of this class. 1681: * If this class is an array class, then a class instance representing 1682: * the <code>Object</code> class is returned. If this class is primitive, 1683: * an interface, or a representation of either the <code>Object</code> 1684: * class or void, then <code>null</code> is returned. 1685: * </p> 1686: * <p> 1687: * If the superclass is a parameterized type, then the 1688: * object returned for this interface reflects the actual type 1689: * parameters used in the source code. Type parameters are created 1690: * using the semantics specified by the <code>ParameterizedType</code> 1691: * interface, and only if an instance has not already been created. 1692: * </p> 1693: * 1694: * @return the superclass of this class. 1695: * @throws GenericSignatureFormatError if the generic signature of the 1696: * class does not comply with that specified by the Java 1697: * Virtual Machine specification, 3rd edition. 1698: * @throws TypeNotPresentException if the superclass refers 1699: * to a non-existant type. 1700: * @throws MalformedParameterizedTypeException if the superclass 1701: * refers to a parameterized type that can not be instantiated for 1702: * some reason. 1703: * @since 1.5 1704: * @see java.lang.reflect.ParameterizedType 1705: */ 1706: public Type getGenericSuperclass() 1707: { 1708: if (isArray()) 1709: return Object.class; 1710: 1711: if (isPrimitive() || isInterface() || this == Object.class) 1712: return null; 1713: 1714: String sig = VMClass.getClassSignature(this); 1715: if (sig == null) 1716: return getSuperclass(); 1717: 1718: ClassSignatureParser p = new ClassSignatureParser(this, sig); 1719: return p.getSuperclassType(); 1720: } 1721: 1722: /** 1723: * Returns an array of <code>TypeVariable</code> objects that represents 1724: * the type variables declared by this class, in declaration order. 1725: * An array of size zero is returned if this class has no type 1726: * variables. 1727: * 1728: * @return the type variables associated with this class. 1729: * @throws GenericSignatureFormatError if the generic signature does 1730: * not conform to the format specified in the Virtual Machine 1731: * specification, version 3. 1732: * @since 1.5 1733: */ 1734: /* FIXME[GENERICS]: Should return TypeVariable<Class<T>> */ 1735: public TypeVariable[] getTypeParameters() 1736: { 1737: String sig = VMClass.getClassSignature(this); 1738: if (sig == null) 1739: return new TypeVariable[0]; 1740: 1741: ClassSignatureParser p = new ClassSignatureParser(this, sig); 1742: return p.getTypeParameters(); 1743: } 1744: 1745: /** 1746: * Returns true if an annotation for the specified type is associated 1747: * with this class. This is primarily a short-hand for using marker 1748: * annotations. 1749: * 1750: * @param annotationClass the type of annotation to look for. 1751: * @return true if an annotation exists for the specified type. 1752: * @since 1.5 1753: */ 1754: /* FIXME[GENERICS]: Should be Class<? extends Annotation> */ 1755: public boolean isAnnotationPresent(Class 1756: annotationClass) 1757: { 1758: return getAnnotation(annotationClass) != null; 1759: } 1760: 1761: /** 1762: * Returns true if this object represents an anonymous class. 1763: * 1764: * @return true if this object represents an anonymous class. 1765: * @since 1.5 1766: */ 1767: public boolean isAnonymousClass() 1768: { 1769: return VMClass.isAnonymousClass(this); 1770: } 1771: 1772: /** 1773: * Returns true if this object represents an local class. 1774: * 1775: * @return true if this object represents an local class. 1776: * @since 1.5 1777: */ 1778: public boolean isLocalClass() 1779: { 1780: return VMClass.isLocalClass(this); 1781: } 1782: 1783: /** 1784: * Returns true if this object represents an member class. 1785: * 1786: * @return true if this object represents an member class. 1787: * @since 1.5 1788: */ 1789: public boolean isMemberClass() 1790: { 1791: return VMClass.isMemberClass(this); 1792: } 1793: 1794: 1795: }
GNU Classpath (0.92) |