src/share/classes/java/lang/Class.java

Print this page




 248      * @since     1.2
 249      */
 250     public static Class<?> forName(String name, boolean initialize,
 251                                    ClassLoader loader)
 252         throws ClassNotFoundException
 253     {
 254         if (loader == null) {
 255             SecurityManager sm = System.getSecurityManager();
 256             if (sm != null) {
 257                 ClassLoader ccl = ClassLoader.getCallerClassLoader();
 258                 if (ccl != null) {
 259                     sm.checkPermission(
 260                         SecurityConstants.GET_CLASSLOADER_PERMISSION);
 261                 }
 262             }
 263         }
 264         return forName0(name, initialize, loader);
 265     }
 266 
 267     /** Called after security checks have been made. */
 268     private static native Class forName0(String name, boolean initialize,
 269                                             ClassLoader loader)
 270         throws ClassNotFoundException;
 271 
 272     /**
 273      * Creates a new instance of the class represented by this {@code Class}
 274      * object.  The class is instantiated as if by a {@code new}
 275      * expression with an empty argument list.  The class is initialized if it
 276      * has not already been initialized.
 277      *
 278      * <p>Note that this method propagates any exception thrown by the
 279      * nullary constructor, including a checked exception.  Use of
 280      * this method effectively bypasses the compile-time exception
 281      * checking that would otherwise be performed by the compiler.
 282      * The {@link
 283      * java.lang.reflect.Constructor#newInstance(java.lang.Object...)
 284      * Constructor.newInstance} method avoids this problem by wrapping
 285      * any exception thrown by the constructor in a (checked) {@link
 286      * java.lang.reflect.InvocationTargetException}.
 287      *
 288      * @return     a newly allocated instance of the class represented by this


 322         if (System.getSecurityManager() != null) {
 323             checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader());
 324         }
 325         return newInstance0();
 326     }
 327 
 328     private T newInstance0()
 329         throws InstantiationException, IllegalAccessException
 330     {
 331         // NOTE: the following code may not be strictly correct under
 332         // the current Java memory model.
 333 
 334         // Constructor lookup
 335         if (cachedConstructor == null) {
 336             if (this == Class.class) {
 337                 throw new IllegalAccessException(
 338                     "Can not call newInstance() on the Class for java.lang.Class"
 339                 );
 340             }
 341             try {
 342                 Class[] empty = {};
 343                 final Constructor<T> c = getConstructor0(empty, Member.DECLARED);
 344                 // Disable accessibility checks on the constructor
 345                 // since we have to do the security check here anyway
 346                 // (the stack depth is wrong for the Constructor's
 347                 // security check to work)
 348                 java.security.AccessController.doPrivileged(
 349                     new java.security.PrivilegedAction<Void>() {
 350                         public Void run() {
 351                                 c.setAccessible(true);
 352                                 return null;
 353                             }
 354                         });
 355                 cachedConstructor = c;
 356             } catch (NoSuchMethodException e) {
 357                 throw new InstantiationException(getName());
 358             }
 359         }
 360         Constructor<T> tmpConstructor = cachedConstructor;
 361         // Security check (same as in java.lang.reflect.Constructor)
 362         int modifiers = tmpConstructor.getModifiers();
 363         if (!Reflection.quickCheckMemberAccess(this, modifiers)) {
 364             Class caller = Reflection.getCallerClass(3);
 365             if (newInstanceCallerCache != caller) {
 366                 Reflection.ensureMemberAccess(caller, this, null, modifiers);
 367                 newInstanceCallerCache = caller;
 368             }
 369         }
 370         // Run constructor
 371         try {
 372             return tmpConstructor.newInstance((Object[])null);
 373         } catch (InvocationTargetException e) {
 374             Unsafe.getUnsafe().throwException(e.getTargetException());
 375             // Not reached
 376             return null;
 377         }
 378     }
 379     private volatile transient Constructor<T> cachedConstructor;
 380     private volatile transient Class       newInstanceCallerCache;
 381 
 382 
 383     /**
 384      * Determines if the specified {@code Object} is assignment-compatible
 385      * with the object represented by this {@code Class}.  This method is
 386      * the dynamic equivalent of the Java language {@code instanceof}
 387      * operator. The method returns {@code true} if the specified
 388      * {@code Object} argument is non-null and can be cast to the
 389      * reference type represented by this {@code Class} object without
 390      * raising a {@code ClassCastException.} It returns {@code false}
 391      * otherwise.
 392      *
 393      * <p> Specifically, if this {@code Class} object represents a
 394      * declared class, this method returns {@code true} if the specified
 395      * {@code Object} argument is an instance of the represented class (or
 396      * of any of its subclasses); it returns {@code false} otherwise. If
 397      * this {@code Class} object represents an array class, this method
 398      * returns {@code true} if the specified {@code Object} argument
 399      * can be converted to an object of the array class by an identity
 400      * conversion or by a widening reference conversion; it returns


 621 
 622     /**
 623      * Returns an array of {@code TypeVariable} objects that represent the
 624      * type variables declared by the generic declaration represented by this
 625      * {@code GenericDeclaration} object, in declaration order.  Returns an
 626      * array of length 0 if the underlying generic declaration declares no type
 627      * variables.
 628      *
 629      * @return an array of {@code TypeVariable} objects that represent
 630      *     the type variables declared by this generic declaration
 631      * @throws java.lang.reflect.GenericSignatureFormatError if the generic
 632      *     signature of this generic declaration does not conform to
 633      *     the format specified in the Java Virtual Machine Specification,
 634      *     3rd edition
 635      * @since 1.5
 636      */
 637     public TypeVariable<Class<T>>[] getTypeParameters() {
 638         if (getGenericSignature() != null)
 639             return (TypeVariable<Class<T>>[])getGenericInfo().getTypeParameters();
 640         else
 641             return (TypeVariable<Class<T>>[])new TypeVariable[0];
 642     }
 643 
 644 
 645     /**
 646      * Returns the {@code Class} representing the superclass of the entity
 647      * (class, interface, primitive type or void) represented by this
 648      * {@code Class}.  If this {@code Class} represents either the
 649      * {@code Object} class, an interface, a primitive type, or void, then
 650      * null is returned.  If this object represents an array class then the
 651      * {@code Class} object representing the {@code Object} class is
 652      * returned.
 653      *
 654      * @return the superclass of the class represented by this object.
 655      */
 656     public native Class<? super T> getSuperclass();
 657 
 658 
 659     /**
 660      * Returns the {@code Type} representing the direct superclass of
 661      * the entity (class, interface, primitive type or void) represented by


 884      *
 885      * In particular, this method returns {@code null} if the underlying
 886      * class is a local or anonymous class immediately enclosed by a type
 887      * declaration, instance initializer or static initializer.
 888      *
 889      * @return the immediately enclosing method of the underlying class, if
 890      *     that class is a local or anonymous class; otherwise {@code null}.
 891      * @since 1.5
 892      */
 893     public Method getEnclosingMethod() {
 894         EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
 895 
 896         if (enclosingInfo == null)
 897             return null;
 898         else {
 899             if (!enclosingInfo.isMethod())
 900                 return null;
 901 
 902             MethodRepository typeInfo = MethodRepository.make(enclosingInfo.getDescriptor(),
 903                                                               getFactory());
 904             Class      returnType       = toClass(typeInfo.getReturnType());
 905             Type []    parameterTypes   = typeInfo.getParameterTypes();
 906             Class<?>[] parameterClasses = new Class<?>[parameterTypes.length];
 907 
 908             // Convert Types to Classes; returned types *should*
 909             // be class objects since the methodDescriptor's used
 910             // don't have generics information
 911             for(int i = 0; i < parameterClasses.length; i++)
 912                 parameterClasses[i] = toClass(parameterTypes[i]);
 913 
 914             /*
 915              * Loop over all declared methods; match method name,
 916              * number of and type of parameters, *and* return
 917              * type.  Matching return type is also necessary
 918              * because of covariant returns, etc.
 919              */
 920             for(Method m: enclosingInfo.getEnclosingClass().getDeclaredMethods()) {
 921                 if (m.getName().equals(enclosingInfo.getName()) ) {
 922                     Class<?>[] candidateParamClasses = m.getParameterTypes();
 923                     if (candidateParamClasses.length == parameterClasses.length) {
 924                         boolean matches = true;


 979                 throw new InternalError("Invalid type in enclosing method information");
 980             }
 981         }
 982 
 983         boolean isPartial() {
 984             return enclosingClass == null || name == null || descriptor == null;
 985         }
 986 
 987         boolean isConstructor() { return !isPartial() && "<init>".equals(name); }
 988 
 989         boolean isMethod() { return !isPartial() && !isConstructor() && !"<clinit>".equals(name); }
 990 
 991         Class<?> getEnclosingClass() { return enclosingClass; }
 992 
 993         String getName() { return name; }
 994 
 995         String getDescriptor() { return descriptor; }
 996 
 997     }
 998 
 999     private static Class toClass(Type o) {
1000         if (o instanceof GenericArrayType)
1001             return Array.newInstance(toClass(((GenericArrayType)o).getGenericComponentType()),
1002                                      0)
1003                 .getClass();
1004         return (Class)o;
1005      }
1006 
1007     /**
1008      * If this {@code Class} object represents a local or anonymous
1009      * class within a constructor, returns a {@link
1010      * java.lang.reflect.Constructor Constructor} object representing
1011      * the immediately enclosing constructor of the underlying
1012      * class. Returns {@code null} otherwise.  In particular, this
1013      * method returns {@code null} if the underlying class is a local
1014      * or anonymous class immediately enclosed by a type declaration,
1015      * instance initializer or static initializer.
1016      *
1017      * @return the immediately enclosing constructor of the underlying class, if
1018      *     that class is a local or anonymous class; otherwise {@code null}.
1019      * @since 1.5
1020      */
1021     public Constructor<?> getEnclosingConstructor() {
1022         EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
1023 
1024         if (enclosingInfo == null)
1025             return null;
1026         else {
1027             if (!enclosingInfo.isConstructor())
1028                 return null;
1029 
1030             ConstructorRepository typeInfo = ConstructorRepository.make(enclosingInfo.getDescriptor(),
1031                                                                         getFactory());
1032             Type []    parameterTypes   = typeInfo.getParameterTypes();
1033             Class<?>[] parameterClasses = new Class<?>[parameterTypes.length];
1034 
1035             // Convert Types to Classes; returned types *should*
1036             // be class objects since the methodDescriptor's used
1037             // don't have generics information
1038             for(int i = 0; i < parameterClasses.length; i++)
1039                 parameterClasses[i] = toClass(parameterTypes[i]);
1040 
1041             /*
1042              * Loop over all declared constructors; match number
1043              * of and type of parameters.
1044              */
1045             for(Constructor c: enclosingInfo.getEnclosingClass().getDeclaredConstructors()) {
1046                 Class<?>[] candidateParamClasses = c.getParameterTypes();
1047                 if (candidateParamClasses.length == parameterClasses.length) {
1048                     boolean matches = true;
1049                     for(int i = 0; i < candidateParamClasses.length; i++) {
1050                         if (!candidateParamClasses[i].equals(parameterClasses[i])) {
1051                             matches = false;
1052                             break;
1053                         }
1054                     }
1055 
1056                     if (matches)
1057                         return c;
1058                 }
1059             }
1060 
1061             throw new InternalError("Enclosing constructor not found");
1062         }
1063     }
1064 
1065 


1287      *             s.checkPackageAccess()} denies access to the package
1288      *             of this class
1289      *
1290      *             </ul>
1291      *
1292      * @since JDK1.1
1293      */
1294     public Class<?>[] getClasses() {
1295         // be very careful not to change the stack depth of this
1296         // checkMemberAccess call for security reasons
1297         // see java.lang.SecurityManager.checkMemberAccess
1298         checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader());
1299 
1300         // Privileged so this implementation can look at DECLARED classes,
1301         // something the caller might not have privilege to do.  The code here
1302         // is allowed to look at DECLARED classes because (1) it does not hand
1303         // out anything other than public members and (2) public member access
1304         // has already been ok'd by the SecurityManager.
1305 
1306         return java.security.AccessController.doPrivileged(
1307             new java.security.PrivilegedAction<Class[]>() {
1308                 public Class[] run() {
1309                     List<Class> list = new ArrayList<Class>();
1310                     Class currentClass = Class.this;
1311                     while (currentClass != null) {
1312                         Class[] members = currentClass.getDeclaredClasses();
1313                         for (int i = 0; i < members.length; i++) {
1314                             if (Modifier.isPublic(members[i].getModifiers())) {
1315                                 list.add(members[i]);
1316                             }
1317                         }
1318                         currentClass = currentClass.getSuperclass();
1319                     }
1320                     return list.toArray(new Class[0]);
1321                 }
1322             });
1323     }
1324 
1325 
1326     /**
1327      * Returns an array containing {@code Field} objects reflecting all
1328      * the accessible public fields of the class or interface represented by
1329      * this {@code Class} object.  The elements in the array returned are
1330      * not sorted and are not in any particular order.  This method returns an
1331      * array of length 0 if the class or interface has no accessible public
1332      * fields, or if it represents an array class, a primitive type, or void.


2174             if ((ccl != null) && (ccl != cl) &&
2175                   ((cl == null) || !cl.isAncestor(ccl))) {
2176                 String name = this.getName();
2177                 int i = name.lastIndexOf('.');
2178                 if (i != -1) {
2179                     s.checkPackageAccess(name.substring(0, i));
2180                 }
2181             }
2182         }
2183     }
2184 
2185     /**
2186      * Add a package name prefix if the name is not absolute Remove leading "/"
2187      * if name is absolute
2188      */
2189     private String resolveName(String name) {
2190         if (name == null) {
2191             return name;
2192         }
2193         if (!name.startsWith("/")) {
2194             Class c = this;
2195             while (c.isArray()) {
2196                 c = c.getComponentType();
2197             }
2198             String baseName = c.getName();
2199             int index = baseName.lastIndexOf('.');
2200             if (index != -1) {
2201                 name = baseName.substring(0, index).replace('.', '/')
2202                     +"/"+name;
2203             }
2204         } else {
2205             name = name.substring(1);
2206         }
2207         return name;
2208     }
2209 
2210     /**
2211      * Reflection support.
2212      */
2213 
2214     // Caches for certain reflective results


2548         if (useCaches) {
2549             clearCachesOnClassRedefinition();
2550             if (publicMethods != null) {
2551                 res = publicMethods.get();
2552             }
2553             if (res != null) return res;
2554         }
2555 
2556         // No cached value available; compute value recursively.
2557         // Start by fetching public declared methods
2558         MethodArray methods = new MethodArray();
2559         {
2560             Method[] tmp = privateGetDeclaredMethods(true);
2561             methods.addAll(tmp);
2562         }
2563         // Now recur over superclass and direct superinterfaces.
2564         // Go over superinterfaces first so we can more easily filter
2565         // out concrete implementations inherited from superclasses at
2566         // the end.
2567         MethodArray inheritedMethods = new MethodArray();
2568         Class[] interfaces = getInterfaces();
2569         for (int i = 0; i < interfaces.length; i++) {
2570             inheritedMethods.addAll(interfaces[i].privateGetPublicMethods());
2571         }
2572         if (!isInterface()) {
2573             Class c = getSuperclass();
2574             if (c != null) {
2575                 MethodArray supers = new MethodArray();
2576                 supers.addAll(c.privateGetPublicMethods());
2577                 // Filter out concrete implementations of any
2578                 // interface methods
2579                 for (int i = 0; i < supers.length(); i++) {
2580                     Method m = supers.get(i);
2581                     if (m != null && !Modifier.isAbstract(m.getModifiers())) {
2582                         inheritedMethods.removeByNameAndSignature(m);
2583                     }
2584                 }
2585                 // Insert superclass's inherited methods before
2586                 // superinterfaces' to satisfy getMethod's search
2587                 // order
2588                 supers.addAll(inheritedMethods);
2589                 inheritedMethods = supers;
2590             }
2591         }
2592         // Filter out all local methods from inherited ones
2593         for (int i = 0; i < methods.length(); i++) {


2615                 return getReflectionFactory().copyField(fields[i]);
2616             }
2617         }
2618         return null;
2619     }
2620 
2621     private Field getField0(String name) throws NoSuchFieldException {
2622         // Note: the intent is that the search algorithm this routine
2623         // uses be equivalent to the ordering imposed by
2624         // privateGetPublicFields(). It fetches only the declared
2625         // public fields for each class, however, to reduce the number
2626         // of Field objects which have to be created for the common
2627         // case where the field being requested is declared in the
2628         // class which is being queried.
2629         Field res = null;
2630         // Search declared public fields
2631         if ((res = searchFields(privateGetDeclaredFields(true), name)) != null) {
2632             return res;
2633         }
2634         // Direct superinterfaces, recursively
2635         Class[] interfaces = getInterfaces();
2636         for (int i = 0; i < interfaces.length; i++) {
2637             Class c = interfaces[i];
2638             if ((res = c.getField0(name)) != null) {
2639                 return res;
2640             }
2641         }
2642         // Direct superclass, recursively
2643         if (!isInterface()) {
2644             Class c = getSuperclass();
2645             if (c != null) {
2646                 if ((res = c.getField0(name)) != null) {
2647                     return res;
2648                 }
2649             }
2650         }
2651         return null;
2652     }
2653 
2654     private static Method searchMethods(Method[] methods,
2655                                         String name,
2656                                         Class[] parameterTypes)
2657     {
2658         Method res = null;
2659         String internedName = name.intern();
2660         for (int i = 0; i < methods.length; i++) {
2661             Method m = methods[i];
2662             if (m.getName() == internedName
2663                 && arrayContentsEq(parameterTypes, m.getParameterTypes())
2664                 && (res == null
2665                     || res.getReturnType().isAssignableFrom(m.getReturnType())))
2666                 res = m;
2667         }
2668 
2669         return (res == null ? res : getReflectionFactory().copyMethod(res));
2670     }
2671 
2672 
2673     private Method getMethod0(String name, Class[] parameterTypes) {
2674         // Note: the intent is that the search algorithm this routine
2675         // uses be equivalent to the ordering imposed by
2676         // privateGetPublicMethods(). It fetches only the declared
2677         // public methods for each class, however, to reduce the
2678         // number of Method objects which have to be created for the
2679         // common case where the method being requested is declared in
2680         // the class which is being queried.
2681         Method res = null;
2682         // Search declared public methods
2683         if ((res = searchMethods(privateGetDeclaredMethods(true),
2684                                  name,
2685                                  parameterTypes)) != null) {
2686             return res;
2687         }
2688         // Search superclass's methods
2689         if (!isInterface()) {
2690             Class c = getSuperclass();
2691             if (c != null) {
2692                 if ((res = c.getMethod0(name, parameterTypes)) != null) {
2693                     return res;
2694                 }
2695             }
2696         }
2697         // Search superinterfaces' methods
2698         Class[] interfaces = getInterfaces();
2699         for (int i = 0; i < interfaces.length; i++) {
2700             Class c = interfaces[i];
2701             if ((res = c.getMethod0(name, parameterTypes)) != null) {
2702                 return res;
2703             }
2704         }
2705         // Not found
2706         return null;
2707     }
2708 
2709     private Constructor<T> getConstructor0(Class[] parameterTypes,
2710                                         int which) throws NoSuchMethodException
2711     {
2712         Constructor<T>[] constructors = privateGetDeclaredConstructors((which == Member.PUBLIC));
2713         for (Constructor<T> constructor : constructors) {
2714             if (arrayContentsEq(parameterTypes,
2715                                 constructor.getParameterTypes())) {
2716                 return getReflectionFactory().copyConstructor(constructor);
2717             }
2718         }
2719         throw new NoSuchMethodException(getName() + ".<init>" + argumentTypesToString(parameterTypes));
2720     }
2721 
2722     //
2723     // Other helpers and base implementation
2724     //
2725 
2726     private static boolean arrayContentsEq(Object[] a1, Object[] a2) {
2727         if (a1 == null) {
2728             return a2 == null || a2.length == 0;
2729         }


2758         Method[] out = new Method[arg.length];
2759         ReflectionFactory fact = getReflectionFactory();
2760         for (int i = 0; i < arg.length; i++) {
2761             out[i] = fact.copyMethod(arg[i]);
2762         }
2763         return out;
2764     }
2765 
2766     private static <U> Constructor<U>[] copyConstructors(Constructor<U>[] arg) {
2767         Constructor<U>[] out = arg.clone();
2768         ReflectionFactory fact = getReflectionFactory();
2769         for (int i = 0; i < out.length; i++) {
2770             out[i] = fact.copyConstructor(out[i]);
2771         }
2772         return out;
2773     }
2774 
2775     private native Field[]       getDeclaredFields0(boolean publicOnly);
2776     private native Method[]      getDeclaredMethods0(boolean publicOnly);
2777     private native Constructor<T>[] getDeclaredConstructors0(boolean publicOnly);
2778     private native Class[]   getDeclaredClasses0();
2779 
2780     private static String        argumentTypesToString(Class[] argTypes) {
2781         StringBuilder buf = new StringBuilder();
2782         buf.append("(");
2783         if (argTypes != null) {
2784             for (int i = 0; i < argTypes.length; i++) {
2785                 if (i > 0) {
2786                     buf.append(", ");
2787                 }
2788                 Class c = argTypes[i];
2789                 buf.append((c == null) ? "null" : c.getName());
2790             }
2791         }
2792         buf.append(")");
2793         return buf.toString();
2794     }
2795 
2796     /** use serialVersionUID from JDK 1.1 for interoperability */
2797     private static final long serialVersionUID = 3206093459760846163L;
2798 
2799 
2800     /**
2801      * Class Class is special cased within the Serialization Stream Protocol.
2802      *
2803      * A Class instance is written initially into an ObjectOutputStream in the
2804      * following format:
2805      * <pre>
2806      *      {@code TC_CLASS} ClassDescriptor
2807      *      A ClassDescriptor is a special cased serialization of
2808      *      a {@code java.io.ObjectStreamClass} instance.


2841      * @see    java.lang.ClassLoader#setDefaultAssertionStatus
2842      * @since  1.4
2843      */
2844     public boolean desiredAssertionStatus() {
2845         ClassLoader loader = getClassLoader();
2846         // If the loader is null this is a system class, so ask the VM
2847         if (loader == null)
2848             return desiredAssertionStatus0(this);
2849 
2850         // If the classloader has been initialized with the assertion
2851         // directives, ask it. Otherwise, ask the VM.
2852         synchronized(loader.assertionLock) {
2853             if (loader.classAssertionStatus != null) {
2854                 return loader.desiredAssertionStatus(getName());
2855             }
2856         }
2857         return desiredAssertionStatus0(this);
2858     }
2859 
2860     // Retrieves the desired assertion status of this class from the VM
2861     private static native boolean desiredAssertionStatus0(Class clazz);
2862 
2863     /**
2864      * Returns true if and only if this class was declared as an enum in the
2865      * source code.
2866      *
2867      * @return true if and only if this class was declared as an enum in the
2868      *     source code
2869      * @since 1.5
2870      */
2871     public boolean isEnum() {
2872         // An enum must both directly extend java.lang.Enum and have
2873         // the ENUM bit set; classes for specialized enum constants
2874         // don't do the former.
2875         return (this.getModifiers() & ENUM) != 0 &&
2876         this.getSuperclass() == java.lang.Enum.class;
2877     }
2878 
2879     // Fetches the factory for reflective objects
2880     private static ReflectionFactory getReflectionFactory() {
2881         if (reflectionFactory == null) {


2962         }
2963         return enumConstants;
2964     }
2965     private volatile transient T[] enumConstants = null;
2966 
2967     /**
2968      * Returns a map from simple name to enum constant.  This package-private
2969      * method is used internally by Enum to implement
2970      *     public static <T extends Enum<T>> T valueOf(Class<T>, String)
2971      * efficiently.  Note that the map is returned by this method is
2972      * created lazily on first use.  Typically it won't ever get created.
2973      */
2974     Map<String, T> enumConstantDirectory() {
2975         if (enumConstantDirectory == null) {
2976             T[] universe = getEnumConstantsShared();
2977             if (universe == null)
2978                 throw new IllegalArgumentException(
2979                     getName() + " is not an enum type");
2980             Map<String, T> m = new HashMap<String, T>(2 * universe.length);
2981             for (T constant : universe)
2982                 m.put(((Enum)constant).name(), constant);
2983             enumConstantDirectory = m;
2984         }
2985         return enumConstantDirectory;
2986     }
2987     private volatile transient Map<String, T> enumConstantDirectory = null;
2988 
2989     /**
2990      * Casts an object to the class or interface represented
2991      * by this {@code Class} object.
2992      *
2993      * @param obj the object to be cast
2994      * @return the object after casting, or null if obj is null
2995      *
2996      * @throws ClassCastException if the object is not
2997      * null and is not assignable to the type T.
2998      *
2999      * @since 1.5
3000      */
3001     public T cast(Object obj) {
3002         if (obj != null && !isInstance(obj))


3060     }
3061 
3062 
3063     /**
3064      * @since 1.5
3065      */
3066     public Annotation[] getAnnotations() {
3067         initAnnotationsIfNecessary();
3068         return AnnotationParser.toArray(annotations);
3069     }
3070 
3071     /**
3072      * @since 1.5
3073      */
3074     public Annotation[] getDeclaredAnnotations()  {
3075         initAnnotationsIfNecessary();
3076         return AnnotationParser.toArray(declaredAnnotations);
3077     }
3078 
3079     // Annotations cache
3080     private transient Map<Class, Annotation> annotations;
3081     private transient Map<Class, Annotation> declaredAnnotations;
3082 
3083     private synchronized void initAnnotationsIfNecessary() {
3084         clearCachesOnClassRedefinition();
3085         if (annotations != null)
3086             return;
3087         declaredAnnotations = AnnotationParser.parseAnnotations(
3088             getRawAnnotations(), getConstantPool(), this);
3089         Class<?> superClass = getSuperclass();
3090         if (superClass == null) {
3091             annotations = declaredAnnotations;
3092         } else {
3093             annotations = new HashMap<Class, Annotation>();
3094             superClass.initAnnotationsIfNecessary();
3095             for (Map.Entry<Class, Annotation> e : superClass.annotations.entrySet()) {
3096                 Class annotationClass = e.getKey();
3097                 if (AnnotationType.getInstance(annotationClass).isInherited())
3098                     annotations.put(annotationClass, e.getValue());
3099             }
3100             annotations.putAll(declaredAnnotations);
3101         }
3102     }
3103 
3104     // Annotation types cache their internal (AnnotationType) form
3105 
3106     private AnnotationType annotationType;
3107 
3108     void setAnnotationType(AnnotationType type) {
3109         annotationType = type;
3110     }
3111 
3112     AnnotationType getAnnotationType() {
3113         return annotationType;
3114     }
3115 }


 248      * @since     1.2
 249      */
 250     public static Class<?> forName(String name, boolean initialize,
 251                                    ClassLoader loader)
 252         throws ClassNotFoundException
 253     {
 254         if (loader == null) {
 255             SecurityManager sm = System.getSecurityManager();
 256             if (sm != null) {
 257                 ClassLoader ccl = ClassLoader.getCallerClassLoader();
 258                 if (ccl != null) {
 259                     sm.checkPermission(
 260                         SecurityConstants.GET_CLASSLOADER_PERMISSION);
 261                 }
 262             }
 263         }
 264         return forName0(name, initialize, loader);
 265     }
 266 
 267     /** Called after security checks have been made. */
 268     private static native Class<?> forName0(String name, boolean initialize,
 269                                             ClassLoader loader)
 270         throws ClassNotFoundException;
 271 
 272     /**
 273      * Creates a new instance of the class represented by this {@code Class}
 274      * object.  The class is instantiated as if by a {@code new}
 275      * expression with an empty argument list.  The class is initialized if it
 276      * has not already been initialized.
 277      *
 278      * <p>Note that this method propagates any exception thrown by the
 279      * nullary constructor, including a checked exception.  Use of
 280      * this method effectively bypasses the compile-time exception
 281      * checking that would otherwise be performed by the compiler.
 282      * The {@link
 283      * java.lang.reflect.Constructor#newInstance(java.lang.Object...)
 284      * Constructor.newInstance} method avoids this problem by wrapping
 285      * any exception thrown by the constructor in a (checked) {@link
 286      * java.lang.reflect.InvocationTargetException}.
 287      *
 288      * @return     a newly allocated instance of the class represented by this


 322         if (System.getSecurityManager() != null) {
 323             checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader());
 324         }
 325         return newInstance0();
 326     }
 327 
 328     private T newInstance0()
 329         throws InstantiationException, IllegalAccessException
 330     {
 331         // NOTE: the following code may not be strictly correct under
 332         // the current Java memory model.
 333 
 334         // Constructor lookup
 335         if (cachedConstructor == null) {
 336             if (this == Class.class) {
 337                 throw new IllegalAccessException(
 338                     "Can not call newInstance() on the Class for java.lang.Class"
 339                 );
 340             }
 341             try {
 342                 Class<?>[] empty = {};
 343                 final Constructor<T> c = getConstructor0(empty, Member.DECLARED);
 344                 // Disable accessibility checks on the constructor
 345                 // since we have to do the security check here anyway
 346                 // (the stack depth is wrong for the Constructor's
 347                 // security check to work)
 348                 java.security.AccessController.doPrivileged(
 349                     new java.security.PrivilegedAction<Void>() {
 350                         public Void run() {
 351                                 c.setAccessible(true);
 352                                 return null;
 353                             }
 354                         });
 355                 cachedConstructor = c;
 356             } catch (NoSuchMethodException e) {
 357                 throw new InstantiationException(getName());
 358             }
 359         }
 360         Constructor<T> tmpConstructor = cachedConstructor;
 361         // Security check (same as in java.lang.reflect.Constructor)
 362         int modifiers = tmpConstructor.getModifiers();
 363         if (!Reflection.quickCheckMemberAccess(this, modifiers)) {
 364             Class<?> caller = Reflection.getCallerClass(3);
 365             if (newInstanceCallerCache != caller) {
 366                 Reflection.ensureMemberAccess(caller, this, null, modifiers);
 367                 newInstanceCallerCache = caller;
 368             }
 369         }
 370         // Run constructor
 371         try {
 372             return tmpConstructor.newInstance((Object[])null);
 373         } catch (InvocationTargetException e) {
 374             Unsafe.getUnsafe().throwException(e.getTargetException());
 375             // Not reached
 376             return null;
 377         }
 378     }
 379     private volatile transient Constructor<T> cachedConstructor;
 380     private volatile transient Class<?>       newInstanceCallerCache;
 381 
 382 
 383     /**
 384      * Determines if the specified {@code Object} is assignment-compatible
 385      * with the object represented by this {@code Class}.  This method is
 386      * the dynamic equivalent of the Java language {@code instanceof}
 387      * operator. The method returns {@code true} if the specified
 388      * {@code Object} argument is non-null and can be cast to the
 389      * reference type represented by this {@code Class} object without
 390      * raising a {@code ClassCastException.} It returns {@code false}
 391      * otherwise.
 392      *
 393      * <p> Specifically, if this {@code Class} object represents a
 394      * declared class, this method returns {@code true} if the specified
 395      * {@code Object} argument is an instance of the represented class (or
 396      * of any of its subclasses); it returns {@code false} otherwise. If
 397      * this {@code Class} object represents an array class, this method
 398      * returns {@code true} if the specified {@code Object} argument
 399      * can be converted to an object of the array class by an identity
 400      * conversion or by a widening reference conversion; it returns


 621 
 622     /**
 623      * Returns an array of {@code TypeVariable} objects that represent the
 624      * type variables declared by the generic declaration represented by this
 625      * {@code GenericDeclaration} object, in declaration order.  Returns an
 626      * array of length 0 if the underlying generic declaration declares no type
 627      * variables.
 628      *
 629      * @return an array of {@code TypeVariable} objects that represent
 630      *     the type variables declared by this generic declaration
 631      * @throws java.lang.reflect.GenericSignatureFormatError if the generic
 632      *     signature of this generic declaration does not conform to
 633      *     the format specified in the Java Virtual Machine Specification,
 634      *     3rd edition
 635      * @since 1.5
 636      */
 637     public TypeVariable<Class<T>>[] getTypeParameters() {
 638         if (getGenericSignature() != null)
 639             return (TypeVariable<Class<T>>[])getGenericInfo().getTypeParameters();
 640         else
 641             return (TypeVariable<Class<T>>[])new TypeVariable<?>[0];
 642     }
 643 
 644 
 645     /**
 646      * Returns the {@code Class} representing the superclass of the entity
 647      * (class, interface, primitive type or void) represented by this
 648      * {@code Class}.  If this {@code Class} represents either the
 649      * {@code Object} class, an interface, a primitive type, or void, then
 650      * null is returned.  If this object represents an array class then the
 651      * {@code Class} object representing the {@code Object} class is
 652      * returned.
 653      *
 654      * @return the superclass of the class represented by this object.
 655      */
 656     public native Class<? super T> getSuperclass();
 657 
 658 
 659     /**
 660      * Returns the {@code Type} representing the direct superclass of
 661      * the entity (class, interface, primitive type or void) represented by


 884      *
 885      * In particular, this method returns {@code null} if the underlying
 886      * class is a local or anonymous class immediately enclosed by a type
 887      * declaration, instance initializer or static initializer.
 888      *
 889      * @return the immediately enclosing method of the underlying class, if
 890      *     that class is a local or anonymous class; otherwise {@code null}.
 891      * @since 1.5
 892      */
 893     public Method getEnclosingMethod() {
 894         EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
 895 
 896         if (enclosingInfo == null)
 897             return null;
 898         else {
 899             if (!enclosingInfo.isMethod())
 900                 return null;
 901 
 902             MethodRepository typeInfo = MethodRepository.make(enclosingInfo.getDescriptor(),
 903                                                               getFactory());
 904             Class<?>   returnType       = toClass(typeInfo.getReturnType());
 905             Type []    parameterTypes   = typeInfo.getParameterTypes();
 906             Class<?>[] parameterClasses = new Class<?>[parameterTypes.length];
 907 
 908             // Convert Types to Classes; returned types *should*
 909             // be class objects since the methodDescriptor's used
 910             // don't have generics information
 911             for(int i = 0; i < parameterClasses.length; i++)
 912                 parameterClasses[i] = toClass(parameterTypes[i]);
 913 
 914             /*
 915              * Loop over all declared methods; match method name,
 916              * number of and type of parameters, *and* return
 917              * type.  Matching return type is also necessary
 918              * because of covariant returns, etc.
 919              */
 920             for(Method m: enclosingInfo.getEnclosingClass().getDeclaredMethods()) {
 921                 if (m.getName().equals(enclosingInfo.getName()) ) {
 922                     Class<?>[] candidateParamClasses = m.getParameterTypes();
 923                     if (candidateParamClasses.length == parameterClasses.length) {
 924                         boolean matches = true;


 979                 throw new InternalError("Invalid type in enclosing method information");
 980             }
 981         }
 982 
 983         boolean isPartial() {
 984             return enclosingClass == null || name == null || descriptor == null;
 985         }
 986 
 987         boolean isConstructor() { return !isPartial() && "<init>".equals(name); }
 988 
 989         boolean isMethod() { return !isPartial() && !isConstructor() && !"<clinit>".equals(name); }
 990 
 991         Class<?> getEnclosingClass() { return enclosingClass; }
 992 
 993         String getName() { return name; }
 994 
 995         String getDescriptor() { return descriptor; }
 996 
 997     }
 998 
 999     private static Class<?> toClass(Type o) {
1000         if (o instanceof GenericArrayType)
1001             return Array.newInstance(toClass(((GenericArrayType)o).getGenericComponentType()),
1002                                      0)
1003                 .getClass();
1004         return (Class<?>)o;
1005      }
1006 
1007     /**
1008      * If this {@code Class} object represents a local or anonymous
1009      * class within a constructor, returns a {@link
1010      * java.lang.reflect.Constructor Constructor} object representing
1011      * the immediately enclosing constructor of the underlying
1012      * class. Returns {@code null} otherwise.  In particular, this
1013      * method returns {@code null} if the underlying class is a local
1014      * or anonymous class immediately enclosed by a type declaration,
1015      * instance initializer or static initializer.
1016      *
1017      * @return the immediately enclosing constructor of the underlying class, if
1018      *     that class is a local or anonymous class; otherwise {@code null}.
1019      * @since 1.5
1020      */
1021     public Constructor<?> getEnclosingConstructor() {
1022         EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
1023 
1024         if (enclosingInfo == null)
1025             return null;
1026         else {
1027             if (!enclosingInfo.isConstructor())
1028                 return null;
1029 
1030             ConstructorRepository typeInfo = ConstructorRepository.make(enclosingInfo.getDescriptor(),
1031                                                                         getFactory());
1032             Type []    parameterTypes   = typeInfo.getParameterTypes();
1033             Class<?>[] parameterClasses = new Class<?>[parameterTypes.length];
1034 
1035             // Convert Types to Classes; returned types *should*
1036             // be class objects since the methodDescriptor's used
1037             // don't have generics information
1038             for(int i = 0; i < parameterClasses.length; i++)
1039                 parameterClasses[i] = toClass(parameterTypes[i]);
1040 
1041             /*
1042              * Loop over all declared constructors; match number
1043              * of and type of parameters.
1044              */
1045             for(Constructor<?> c: enclosingInfo.getEnclosingClass().getDeclaredConstructors()) {
1046                 Class<?>[] candidateParamClasses = c.getParameterTypes();
1047                 if (candidateParamClasses.length == parameterClasses.length) {
1048                     boolean matches = true;
1049                     for(int i = 0; i < candidateParamClasses.length; i++) {
1050                         if (!candidateParamClasses[i].equals(parameterClasses[i])) {
1051                             matches = false;
1052                             break;
1053                         }
1054                     }
1055 
1056                     if (matches)
1057                         return c;
1058                 }
1059             }
1060 
1061             throw new InternalError("Enclosing constructor not found");
1062         }
1063     }
1064 
1065 


1287      *             s.checkPackageAccess()} denies access to the package
1288      *             of this class
1289      *
1290      *             </ul>
1291      *
1292      * @since JDK1.1
1293      */
1294     public Class<?>[] getClasses() {
1295         // be very careful not to change the stack depth of this
1296         // checkMemberAccess call for security reasons
1297         // see java.lang.SecurityManager.checkMemberAccess
1298         checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader());
1299 
1300         // Privileged so this implementation can look at DECLARED classes,
1301         // something the caller might not have privilege to do.  The code here
1302         // is allowed to look at DECLARED classes because (1) it does not hand
1303         // out anything other than public members and (2) public member access
1304         // has already been ok'd by the SecurityManager.
1305 
1306         return java.security.AccessController.doPrivileged(
1307             new java.security.PrivilegedAction<Class<?>[]>() {
1308                 public Class[] run() {
1309                     List<Class<?>> list = new ArrayList<Class<?>>();
1310                     Class<?> currentClass = Class.this;
1311                     while (currentClass != null) {
1312                         Class<?>[] members = currentClass.getDeclaredClasses();
1313                         for (int i = 0; i < members.length; i++) {
1314                             if (Modifier.isPublic(members[i].getModifiers())) {
1315                                 list.add(members[i]);
1316                             }
1317                         }
1318                         currentClass = currentClass.getSuperclass();
1319                     }
1320                     return list.toArray(new Class[0]);
1321                 }
1322             });
1323     }
1324 
1325 
1326     /**
1327      * Returns an array containing {@code Field} objects reflecting all
1328      * the accessible public fields of the class or interface represented by
1329      * this {@code Class} object.  The elements in the array returned are
1330      * not sorted and are not in any particular order.  This method returns an
1331      * array of length 0 if the class or interface has no accessible public
1332      * fields, or if it represents an array class, a primitive type, or void.


2174             if ((ccl != null) && (ccl != cl) &&
2175                   ((cl == null) || !cl.isAncestor(ccl))) {
2176                 String name = this.getName();
2177                 int i = name.lastIndexOf('.');
2178                 if (i != -1) {
2179                     s.checkPackageAccess(name.substring(0, i));
2180                 }
2181             }
2182         }
2183     }
2184 
2185     /**
2186      * Add a package name prefix if the name is not absolute Remove leading "/"
2187      * if name is absolute
2188      */
2189     private String resolveName(String name) {
2190         if (name == null) {
2191             return name;
2192         }
2193         if (!name.startsWith("/")) {
2194             Class<?> c = this;
2195             while (c.isArray()) {
2196                 c = c.getComponentType();
2197             }
2198             String baseName = c.getName();
2199             int index = baseName.lastIndexOf('.');
2200             if (index != -1) {
2201                 name = baseName.substring(0, index).replace('.', '/')
2202                     +"/"+name;
2203             }
2204         } else {
2205             name = name.substring(1);
2206         }
2207         return name;
2208     }
2209 
2210     /**
2211      * Reflection support.
2212      */
2213 
2214     // Caches for certain reflective results


2548         if (useCaches) {
2549             clearCachesOnClassRedefinition();
2550             if (publicMethods != null) {
2551                 res = publicMethods.get();
2552             }
2553             if (res != null) return res;
2554         }
2555 
2556         // No cached value available; compute value recursively.
2557         // Start by fetching public declared methods
2558         MethodArray methods = new MethodArray();
2559         {
2560             Method[] tmp = privateGetDeclaredMethods(true);
2561             methods.addAll(tmp);
2562         }
2563         // Now recur over superclass and direct superinterfaces.
2564         // Go over superinterfaces first so we can more easily filter
2565         // out concrete implementations inherited from superclasses at
2566         // the end.
2567         MethodArray inheritedMethods = new MethodArray();
2568         Class<?>[] interfaces = getInterfaces();
2569         for (int i = 0; i < interfaces.length; i++) {
2570             inheritedMethods.addAll(interfaces[i].privateGetPublicMethods());
2571         }
2572         if (!isInterface()) {
2573             Class<?> c = getSuperclass();
2574             if (c != null) {
2575                 MethodArray supers = new MethodArray();
2576                 supers.addAll(c.privateGetPublicMethods());
2577                 // Filter out concrete implementations of any
2578                 // interface methods
2579                 for (int i = 0; i < supers.length(); i++) {
2580                     Method m = supers.get(i);
2581                     if (m != null && !Modifier.isAbstract(m.getModifiers())) {
2582                         inheritedMethods.removeByNameAndSignature(m);
2583                     }
2584                 }
2585                 // Insert superclass's inherited methods before
2586                 // superinterfaces' to satisfy getMethod's search
2587                 // order
2588                 supers.addAll(inheritedMethods);
2589                 inheritedMethods = supers;
2590             }
2591         }
2592         // Filter out all local methods from inherited ones
2593         for (int i = 0; i < methods.length(); i++) {


2615                 return getReflectionFactory().copyField(fields[i]);
2616             }
2617         }
2618         return null;
2619     }
2620 
2621     private Field getField0(String name) throws NoSuchFieldException {
2622         // Note: the intent is that the search algorithm this routine
2623         // uses be equivalent to the ordering imposed by
2624         // privateGetPublicFields(). It fetches only the declared
2625         // public fields for each class, however, to reduce the number
2626         // of Field objects which have to be created for the common
2627         // case where the field being requested is declared in the
2628         // class which is being queried.
2629         Field res = null;
2630         // Search declared public fields
2631         if ((res = searchFields(privateGetDeclaredFields(true), name)) != null) {
2632             return res;
2633         }
2634         // Direct superinterfaces, recursively
2635         Class<?>[] interfaces = getInterfaces();
2636         for (int i = 0; i < interfaces.length; i++) {
2637             Class<?> c = interfaces[i];
2638             if ((res = c.getField0(name)) != null) {
2639                 return res;
2640             }
2641         }
2642         // Direct superclass, recursively
2643         if (!isInterface()) {
2644             Class<?> c = getSuperclass();
2645             if (c != null) {
2646                 if ((res = c.getField0(name)) != null) {
2647                     return res;
2648                 }
2649             }
2650         }
2651         return null;
2652     }
2653 
2654     private static Method searchMethods(Method[] methods,
2655                                         String name,
2656                                         Class<?>[] parameterTypes)
2657     {
2658         Method res = null;
2659         String internedName = name.intern();
2660         for (int i = 0; i < methods.length; i++) {
2661             Method m = methods[i];
2662             if (m.getName() == internedName
2663                 && arrayContentsEq(parameterTypes, m.getParameterTypes())
2664                 && (res == null
2665                     || res.getReturnType().isAssignableFrom(m.getReturnType())))
2666                 res = m;
2667         }
2668 
2669         return (res == null ? res : getReflectionFactory().copyMethod(res));
2670     }
2671 
2672 
2673     private Method getMethod0(String name, Class<?>[] parameterTypes) {
2674         // Note: the intent is that the search algorithm this routine
2675         // uses be equivalent to the ordering imposed by
2676         // privateGetPublicMethods(). It fetches only the declared
2677         // public methods for each class, however, to reduce the
2678         // number of Method objects which have to be created for the
2679         // common case where the method being requested is declared in
2680         // the class which is being queried.
2681         Method res = null;
2682         // Search declared public methods
2683         if ((res = searchMethods(privateGetDeclaredMethods(true),
2684                                  name,
2685                                  parameterTypes)) != null) {
2686             return res;
2687         }
2688         // Search superclass's methods
2689         if (!isInterface()) {
2690             Class<? super T> c = getSuperclass();
2691             if (c != null) {
2692                 if ((res = c.getMethod0(name, parameterTypes)) != null) {
2693                     return res;
2694                 }
2695             }
2696         }
2697         // Search superinterfaces' methods
2698         Class<?>[] interfaces = getInterfaces();
2699         for (int i = 0; i < interfaces.length; i++) {
2700             Class<?> c = interfaces[i];
2701             if ((res = c.getMethod0(name, parameterTypes)) != null) {
2702                 return res;
2703             }
2704         }
2705         // Not found
2706         return null;
2707     }
2708 
2709     private Constructor<T> getConstructor0(Class<?>[] parameterTypes,
2710                                         int which) throws NoSuchMethodException
2711     {
2712         Constructor<T>[] constructors = privateGetDeclaredConstructors((which == Member.PUBLIC));
2713         for (Constructor<T> constructor : constructors) {
2714             if (arrayContentsEq(parameterTypes,
2715                                 constructor.getParameterTypes())) {
2716                 return getReflectionFactory().copyConstructor(constructor);
2717             }
2718         }
2719         throw new NoSuchMethodException(getName() + ".<init>" + argumentTypesToString(parameterTypes));
2720     }
2721 
2722     //
2723     // Other helpers and base implementation
2724     //
2725 
2726     private static boolean arrayContentsEq(Object[] a1, Object[] a2) {
2727         if (a1 == null) {
2728             return a2 == null || a2.length == 0;
2729         }


2758         Method[] out = new Method[arg.length];
2759         ReflectionFactory fact = getReflectionFactory();
2760         for (int i = 0; i < arg.length; i++) {
2761             out[i] = fact.copyMethod(arg[i]);
2762         }
2763         return out;
2764     }
2765 
2766     private static <U> Constructor<U>[] copyConstructors(Constructor<U>[] arg) {
2767         Constructor<U>[] out = arg.clone();
2768         ReflectionFactory fact = getReflectionFactory();
2769         for (int i = 0; i < out.length; i++) {
2770             out[i] = fact.copyConstructor(out[i]);
2771         }
2772         return out;
2773     }
2774 
2775     private native Field[]       getDeclaredFields0(boolean publicOnly);
2776     private native Method[]      getDeclaredMethods0(boolean publicOnly);
2777     private native Constructor<T>[] getDeclaredConstructors0(boolean publicOnly);
2778     private native Class<?>[]   getDeclaredClasses0();
2779 
2780     private static String        argumentTypesToString(Class<?>[] argTypes) {
2781         StringBuilder buf = new StringBuilder();
2782         buf.append("(");
2783         if (argTypes != null) {
2784             for (int i = 0; i < argTypes.length; i++) {
2785                 if (i > 0) {
2786                     buf.append(", ");
2787                 }
2788                 Class<?> c = argTypes[i];
2789                 buf.append((c == null) ? "null" : c.getName());
2790             }
2791         }
2792         buf.append(")");
2793         return buf.toString();
2794     }
2795 
2796     /** use serialVersionUID from JDK 1.1 for interoperability */
2797     private static final long serialVersionUID = 3206093459760846163L;
2798 
2799 
2800     /**
2801      * Class Class is special cased within the Serialization Stream Protocol.
2802      *
2803      * A Class instance is written initially into an ObjectOutputStream in the
2804      * following format:
2805      * <pre>
2806      *      {@code TC_CLASS} ClassDescriptor
2807      *      A ClassDescriptor is a special cased serialization of
2808      *      a {@code java.io.ObjectStreamClass} instance.


2841      * @see    java.lang.ClassLoader#setDefaultAssertionStatus
2842      * @since  1.4
2843      */
2844     public boolean desiredAssertionStatus() {
2845         ClassLoader loader = getClassLoader();
2846         // If the loader is null this is a system class, so ask the VM
2847         if (loader == null)
2848             return desiredAssertionStatus0(this);
2849 
2850         // If the classloader has been initialized with the assertion
2851         // directives, ask it. Otherwise, ask the VM.
2852         synchronized(loader.assertionLock) {
2853             if (loader.classAssertionStatus != null) {
2854                 return loader.desiredAssertionStatus(getName());
2855             }
2856         }
2857         return desiredAssertionStatus0(this);
2858     }
2859 
2860     // Retrieves the desired assertion status of this class from the VM
2861     private static native boolean desiredAssertionStatus0(Class<?> clazz);
2862 
2863     /**
2864      * Returns true if and only if this class was declared as an enum in the
2865      * source code.
2866      *
2867      * @return true if and only if this class was declared as an enum in the
2868      *     source code
2869      * @since 1.5
2870      */
2871     public boolean isEnum() {
2872         // An enum must both directly extend java.lang.Enum and have
2873         // the ENUM bit set; classes for specialized enum constants
2874         // don't do the former.
2875         return (this.getModifiers() & ENUM) != 0 &&
2876         this.getSuperclass() == java.lang.Enum.class;
2877     }
2878 
2879     // Fetches the factory for reflective objects
2880     private static ReflectionFactory getReflectionFactory() {
2881         if (reflectionFactory == null) {


2962         }
2963         return enumConstants;
2964     }
2965     private volatile transient T[] enumConstants = null;
2966 
2967     /**
2968      * Returns a map from simple name to enum constant.  This package-private
2969      * method is used internally by Enum to implement
2970      *     public static <T extends Enum<T>> T valueOf(Class<T>, String)
2971      * efficiently.  Note that the map is returned by this method is
2972      * created lazily on first use.  Typically it won't ever get created.
2973      */
2974     Map<String, T> enumConstantDirectory() {
2975         if (enumConstantDirectory == null) {
2976             T[] universe = getEnumConstantsShared();
2977             if (universe == null)
2978                 throw new IllegalArgumentException(
2979                     getName() + " is not an enum type");
2980             Map<String, T> m = new HashMap<String, T>(2 * universe.length);
2981             for (T constant : universe)
2982                 m.put(((Enum<?>)constant).name(), constant);
2983             enumConstantDirectory = m;
2984         }
2985         return enumConstantDirectory;
2986     }
2987     private volatile transient Map<String, T> enumConstantDirectory = null;
2988 
2989     /**
2990      * Casts an object to the class or interface represented
2991      * by this {@code Class} object.
2992      *
2993      * @param obj the object to be cast
2994      * @return the object after casting, or null if obj is null
2995      *
2996      * @throws ClassCastException if the object is not
2997      * null and is not assignable to the type T.
2998      *
2999      * @since 1.5
3000      */
3001     public T cast(Object obj) {
3002         if (obj != null && !isInstance(obj))


3060     }
3061 
3062 
3063     /**
3064      * @since 1.5
3065      */
3066     public Annotation[] getAnnotations() {
3067         initAnnotationsIfNecessary();
3068         return AnnotationParser.toArray(annotations);
3069     }
3070 
3071     /**
3072      * @since 1.5
3073      */
3074     public Annotation[] getDeclaredAnnotations()  {
3075         initAnnotationsIfNecessary();
3076         return AnnotationParser.toArray(declaredAnnotations);
3077     }
3078 
3079     // Annotations cache
3080     private transient Map<Class<? extends Annotation>, Annotation> annotations;
3081     private transient Map<Class<? extends Annotation>, Annotation> declaredAnnotations;
3082 
3083     private synchronized void initAnnotationsIfNecessary() {
3084         clearCachesOnClassRedefinition();
3085         if (annotations != null)
3086             return;
3087         declaredAnnotations = AnnotationParser.parseAnnotations(
3088             getRawAnnotations(), getConstantPool(), this);
3089         Class<?> superClass = getSuperclass();
3090         if (superClass == null) {
3091             annotations = declaredAnnotations;
3092         } else {
3093             annotations = new HashMap<Class<? extends Annotation>, Annotation>();
3094             superClass.initAnnotationsIfNecessary();
3095             for (Map.Entry<Class<? extends Annotation>, Annotation> e : superClass.annotations.entrySet()) {
3096                 Class<? extends Annotation> annotationClass = e.getKey();
3097                 if (AnnotationType.getInstance(annotationClass).isInherited())
3098                     annotations.put(annotationClass, e.getValue());
3099             }
3100             annotations.putAll(declaredAnnotations);
3101         }
3102     }
3103 
3104     // Annotation types cache their internal (AnnotationType) form
3105 
3106     private AnnotationType annotationType;
3107 
3108     void setAnnotationType(AnnotationType type) {
3109         annotationType = type;
3110     }
3111 
3112     AnnotationType getAnnotationType() {
3113         return annotationType;
3114     }
3115 }