rt/emul/mini/src/main/java/java/lang/Class.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Mon, 25 Mar 2013 16:16:30 +0100
branchmodel
changeset 886 88540bb74300
parent 772 d382dacfd73f
child 933 0cb657a2b888
permissions -rw-r--r--
Class.isAssignableFrom and primitive types works better now
     1 /*
     2  * Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Oracle designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Oracle in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    22  * or visit www.oracle.com if you need additional information or have any
    23  * questions.
    24  */
    25 
    26 package java.lang;
    27 
    28 import java.io.ByteArrayInputStream;
    29 import org.apidesign.bck2brwsr.emul.reflect.AnnotationImpl;
    30 import java.io.InputStream;
    31 import java.lang.annotation.Annotation;
    32 import java.lang.reflect.Field;
    33 import java.lang.reflect.Method;
    34 import java.lang.reflect.TypeVariable;
    35 import java.net.URL;
    36 import org.apidesign.bck2brwsr.core.JavaScriptBody;
    37 import org.apidesign.bck2brwsr.emul.reflect.MethodImpl;
    38 
    39 /**
    40  * Instances of the class {@code Class} represent classes and
    41  * interfaces in a running Java application.  An enum is a kind of
    42  * class and an annotation is a kind of interface.  Every array also
    43  * belongs to a class that is reflected as a {@code Class} object
    44  * that is shared by all arrays with the same element type and number
    45  * of dimensions.  The primitive Java types ({@code boolean},
    46  * {@code byte}, {@code char}, {@code short},
    47  * {@code int}, {@code long}, {@code float}, and
    48  * {@code double}), and the keyword {@code void} are also
    49  * represented as {@code Class} objects.
    50  *
    51  * <p> {@code Class} has no public constructor. Instead {@code Class}
    52  * objects are constructed automatically by the Java Virtual Machine as classes
    53  * are loaded and by calls to the {@code defineClass} method in the class
    54  * loader.
    55  *
    56  * <p> The following example uses a {@code Class} object to print the
    57  * class name of an object:
    58  *
    59  * <p> <blockquote><pre>
    60  *     void printClassName(Object obj) {
    61  *         System.out.println("The class of " + obj +
    62  *                            " is " + obj.getClass().getName());
    63  *     }
    64  * </pre></blockquote>
    65  *
    66  * <p> It is also possible to get the {@code Class} object for a named
    67  * type (or for void) using a class literal.  See Section 15.8.2 of
    68  * <cite>The Java&trade; Language Specification</cite>.
    69  * For example:
    70  *
    71  * <p> <blockquote>
    72  *     {@code System.out.println("The name of class Foo is: "+Foo.class.getName());}
    73  * </blockquote>
    74  *
    75  * @param <T> the type of the class modeled by this {@code Class}
    76  * object.  For example, the type of {@code String.class} is {@code
    77  * Class<String>}.  Use {@code Class<?>} if the class being modeled is
    78  * unknown.
    79  *
    80  * @author  unascribed
    81  * @see     java.lang.ClassLoader#defineClass(byte[], int, int)
    82  * @since   JDK1.0
    83  */
    84 public final
    85     class Class<T> implements java.io.Serializable,
    86                               java.lang.reflect.GenericDeclaration,
    87                               java.lang.reflect.Type,
    88                               java.lang.reflect.AnnotatedElement {
    89     private static final int ANNOTATION= 0x00002000;
    90     private static final int ENUM      = 0x00004000;
    91     private static final int SYNTHETIC = 0x00001000;
    92 
    93     /*
    94      * Constructor. Only the Java Virtual Machine creates Class
    95      * objects.
    96      */
    97     private Class() {}
    98 
    99 
   100     /**
   101      * Converts the object to a string. The string representation is the
   102      * string "class" or "interface", followed by a space, and then by the
   103      * fully qualified name of the class in the format returned by
   104      * {@code getName}.  If this {@code Class} object represents a
   105      * primitive type, this method returns the name of the primitive type.  If
   106      * this {@code Class} object represents void this method returns
   107      * "void".
   108      *
   109      * @return a string representation of this class object.
   110      */
   111     public String toString() {
   112         return (isInterface() ? "interface " : (isPrimitive() ? "" : "class "))
   113             + getName();
   114     }
   115 
   116 
   117     /**
   118      * Returns the {@code Class} object associated with the class or
   119      * interface with the given string name.  Invoking this method is
   120      * equivalent to:
   121      *
   122      * <blockquote>
   123      *  {@code Class.forName(className, true, currentLoader)}
   124      * </blockquote>
   125      *
   126      * where {@code currentLoader} denotes the defining class loader of
   127      * the current class.
   128      *
   129      * <p> For example, the following code fragment returns the
   130      * runtime {@code Class} descriptor for the class named
   131      * {@code java.lang.Thread}:
   132      *
   133      * <blockquote>
   134      *   {@code Class t = Class.forName("java.lang.Thread")}
   135      * </blockquote>
   136      * <p>
   137      * A call to {@code forName("X")} causes the class named
   138      * {@code X} to be initialized.
   139      *
   140      * @param      className   the fully qualified name of the desired class.
   141      * @return     the {@code Class} object for the class with the
   142      *             specified name.
   143      * @exception LinkageError if the linkage fails
   144      * @exception ExceptionInInitializerError if the initialization provoked
   145      *            by this method fails
   146      * @exception ClassNotFoundException if the class cannot be located
   147      */
   148     public static Class<?> forName(String className)
   149     throws ClassNotFoundException {
   150         if (className.startsWith("[")) {
   151             Class<?> arrType = defineArray(className);
   152             Class<?> c = arrType;
   153             while (c != null && c.isArray()) {
   154                 c = c.getComponentType0(); // verify component type is sane
   155             }
   156             return arrType;
   157         }
   158         Class<?> c = loadCls(className, className.replace('.', '_'));
   159         if (c == null) {
   160             throw new ClassNotFoundException(className);
   161         }
   162         return c;
   163     }
   164 
   165 
   166     /**
   167      * Returns the {@code Class} object associated with the class or
   168      * interface with the given string name, using the given class loader.
   169      * Given the fully qualified name for a class or interface (in the same
   170      * format returned by {@code getName}) this method attempts to
   171      * locate, load, and link the class or interface.  The specified class
   172      * loader is used to load the class or interface.  If the parameter
   173      * {@code loader} is null, the class is loaded through the bootstrap
   174      * class loader.  The class is initialized only if the
   175      * {@code initialize} parameter is {@code true} and if it has
   176      * not been initialized earlier.
   177      *
   178      * <p> If {@code name} denotes a primitive type or void, an attempt
   179      * will be made to locate a user-defined class in the unnamed package whose
   180      * name is {@code name}. Therefore, this method cannot be used to
   181      * obtain any of the {@code Class} objects representing primitive
   182      * types or void.
   183      *
   184      * <p> If {@code name} denotes an array class, the component type of
   185      * the array class is loaded but not initialized.
   186      *
   187      * <p> For example, in an instance method the expression:
   188      *
   189      * <blockquote>
   190      *  {@code Class.forName("Foo")}
   191      * </blockquote>
   192      *
   193      * is equivalent to:
   194      *
   195      * <blockquote>
   196      *  {@code Class.forName("Foo", true, this.getClass().getClassLoader())}
   197      * </blockquote>
   198      *
   199      * Note that this method throws errors related to loading, linking or
   200      * initializing as specified in Sections 12.2, 12.3 and 12.4 of <em>The
   201      * Java Language Specification</em>.
   202      * Note that this method does not check whether the requested class
   203      * is accessible to its caller.
   204      *
   205      * <p> If the {@code loader} is {@code null}, and a security
   206      * manager is present, and the caller's class loader is not null, then this
   207      * method calls the security manager's {@code checkPermission} method
   208      * with a {@code RuntimePermission("getClassLoader")} permission to
   209      * ensure it's ok to access the bootstrap class loader.
   210      *
   211      * @param name       fully qualified name of the desired class
   212      * @param initialize whether the class must be initialized
   213      * @param loader     class loader from which the class must be loaded
   214      * @return           class object representing the desired class
   215      *
   216      * @exception LinkageError if the linkage fails
   217      * @exception ExceptionInInitializerError if the initialization provoked
   218      *            by this method fails
   219      * @exception ClassNotFoundException if the class cannot be located by
   220      *            the specified class loader
   221      *
   222      * @see       java.lang.Class#forName(String)
   223      * @see       java.lang.ClassLoader
   224      * @since     1.2
   225      */
   226     public static Class<?> forName(String name, boolean initialize,
   227                                    ClassLoader loader)
   228         throws ClassNotFoundException
   229     {
   230         return forName(name);
   231     }
   232     
   233     @JavaScriptBody(args = {"n", "c" }, body =
   234         "if (!vm[c]) {\n"
   235       + "  if (vm.loadClass) {\n"
   236       + "    vm.loadClass(n);\n"
   237       + "  }\n"
   238       + "  if (!vm[c]) return null;\n"
   239       + "}\n"
   240       + "vm[c](false);"
   241       + "return vm[c].$class;"
   242     )
   243     private static native Class<?> loadCls(String n, String c);
   244 
   245 
   246     /**
   247      * Creates a new instance of the class represented by this {@code Class}
   248      * object.  The class is instantiated as if by a {@code new}
   249      * expression with an empty argument list.  The class is initialized if it
   250      * has not already been initialized.
   251      *
   252      * <p>Note that this method propagates any exception thrown by the
   253      * nullary constructor, including a checked exception.  Use of
   254      * this method effectively bypasses the compile-time exception
   255      * checking that would otherwise be performed by the compiler.
   256      * The {@link
   257      * java.lang.reflect.Constructor#newInstance(java.lang.Object...)
   258      * Constructor.newInstance} method avoids this problem by wrapping
   259      * any exception thrown by the constructor in a (checked) {@link
   260      * java.lang.reflect.InvocationTargetException}.
   261      *
   262      * @return     a newly allocated instance of the class represented by this
   263      *             object.
   264      * @exception  IllegalAccessException  if the class or its nullary
   265      *               constructor is not accessible.
   266      * @exception  InstantiationException
   267      *               if this {@code Class} represents an abstract class,
   268      *               an interface, an array class, a primitive type, or void;
   269      *               or if the class has no nullary constructor;
   270      *               or if the instantiation fails for some other reason.
   271      * @exception  ExceptionInInitializerError if the initialization
   272      *               provoked by this method fails.
   273      * @exception  SecurityException
   274      *             If a security manager, <i>s</i>, is present and any of the
   275      *             following conditions is met:
   276      *
   277      *             <ul>
   278      *
   279      *             <li> invocation of
   280      *             {@link SecurityManager#checkMemberAccess
   281      *             s.checkMemberAccess(this, Member.PUBLIC)} denies
   282      *             creation of new instances of this class
   283      *
   284      *             <li> the caller's class loader is not the same as or an
   285      *             ancestor of the class loader for the current class and
   286      *             invocation of {@link SecurityManager#checkPackageAccess
   287      *             s.checkPackageAccess()} denies access to the package
   288      *             of this class
   289      *
   290      *             </ul>
   291      *
   292      */
   293     @JavaScriptBody(args = { "self", "illegal" }, body =
   294           "\nvar c = self.cnstr;"
   295         + "\nif (c['cons__V']) {"
   296         + "\n  if ((c.cons__V.access & 0x1) != 0) {"
   297         + "\n    var inst = c();"
   298         + "\n    c.cons__V.call(inst);"
   299         + "\n    return inst;"
   300         + "\n  }"
   301         + "\n  return illegal;"
   302         + "\n}"
   303         + "\nreturn null;"
   304     )
   305     private static native Object newInstance0(Class<?> self, Object illegal);
   306     
   307     public T newInstance()
   308         throws InstantiationException, IllegalAccessException
   309     {
   310         Object illegal = new Object();
   311         Object inst = newInstance0(this, illegal);
   312         if (inst == null) {
   313             throw new InstantiationException(getName());
   314         }
   315         if (inst == illegal) {
   316             throw new IllegalAccessException();
   317         }
   318         return (T)inst;
   319     }
   320 
   321     /**
   322      * Determines if the specified {@code Object} is assignment-compatible
   323      * with the object represented by this {@code Class}.  This method is
   324      * the dynamic equivalent of the Java language {@code instanceof}
   325      * operator. The method returns {@code true} if the specified
   326      * {@code Object} argument is non-null and can be cast to the
   327      * reference type represented by this {@code Class} object without
   328      * raising a {@code ClassCastException.} It returns {@code false}
   329      * otherwise.
   330      *
   331      * <p> Specifically, if this {@code Class} object represents a
   332      * declared class, this method returns {@code true} if the specified
   333      * {@code Object} argument is an instance of the represented class (or
   334      * of any of its subclasses); it returns {@code false} otherwise. If
   335      * this {@code Class} object represents an array class, this method
   336      * returns {@code true} if the specified {@code Object} argument
   337      * can be converted to an object of the array class by an identity
   338      * conversion or by a widening reference conversion; it returns
   339      * {@code false} otherwise. If this {@code Class} object
   340      * represents an interface, this method returns {@code true} if the
   341      * class or any superclass of the specified {@code Object} argument
   342      * implements this interface; it returns {@code false} otherwise. If
   343      * this {@code Class} object represents a primitive type, this method
   344      * returns {@code false}.
   345      *
   346      * @param   obj the object to check
   347      * @return  true if {@code obj} is an instance of this class
   348      *
   349      * @since JDK1.1
   350      */
   351     public boolean isInstance(Object obj) {
   352         if (obj == null) {
   353             return false;
   354         }
   355         if (isArray()) {
   356             return isAssignableFrom(obj.getClass());
   357         }
   358         
   359         String prop = "$instOf_" + getName().replace('.', '_');
   360         return hasProperty(obj, prop);
   361     }
   362     
   363     @JavaScriptBody(args = { "who", "prop" }, body = 
   364         "if (who[prop]) return true; else return false;"
   365     )
   366     private static native boolean hasProperty(Object who, String prop);
   367 
   368 
   369     /**
   370      * Determines if the class or interface represented by this
   371      * {@code Class} object is either the same as, or is a superclass or
   372      * superinterface of, the class or interface represented by the specified
   373      * {@code Class} parameter. It returns {@code true} if so;
   374      * otherwise it returns {@code false}. If this {@code Class}
   375      * object represents a primitive type, this method returns
   376      * {@code true} if the specified {@code Class} parameter is
   377      * exactly this {@code Class} object; otherwise it returns
   378      * {@code false}.
   379      *
   380      * <p> Specifically, this method tests whether the type represented by the
   381      * specified {@code Class} parameter can be converted to the type
   382      * represented by this {@code Class} object via an identity conversion
   383      * or via a widening reference conversion. See <em>The Java Language
   384      * Specification</em>, sections 5.1.1 and 5.1.4 , for details.
   385      *
   386      * @param cls the {@code Class} object to be checked
   387      * @return the {@code boolean} value indicating whether objects of the
   388      * type {@code cls} can be assigned to objects of this class
   389      * @exception NullPointerException if the specified Class parameter is
   390      *            null.
   391      * @since JDK1.1
   392      */
   393     public boolean isAssignableFrom(Class<?> cls) {
   394         if (this == cls) {
   395             return true;
   396         }
   397         
   398         if (isArray()) {
   399             final Class<?> cmpType = cls.getComponentType();
   400             if (isPrimitive()) {
   401                 return this == cmpType;
   402             }
   403             return cmpType != null && getComponentType().isAssignableFrom(cmpType);
   404         }
   405         if (isPrimitive()) {
   406             return false;
   407         } else {
   408             if (cls.isPrimitive()) {
   409                 return false;
   410             }
   411             String prop = "$instOf_" + getName().replace('.', '_');
   412             return hasCnstrProperty(cls, prop);
   413         }
   414     }
   415 
   416     @JavaScriptBody(args = { "who", "prop" }, body = 
   417         "if (who.cnstr.prototype[prop]) return true; else return false;"
   418     )
   419     private static native boolean hasCnstrProperty(Object who, String prop);
   420     
   421     
   422     /**
   423      * Determines if the specified {@code Class} object represents an
   424      * interface type.
   425      *
   426      * @return  {@code true} if this object represents an interface;
   427      *          {@code false} otherwise.
   428      */
   429     public boolean isInterface() {
   430         return (getAccess() & 0x200) != 0;
   431     }
   432     
   433     @JavaScriptBody(args = {}, body = "return this.access;")
   434     private native int getAccess();
   435 
   436 
   437     /**
   438      * Determines if this {@code Class} object represents an array class.
   439      *
   440      * @return  {@code true} if this object represents an array class;
   441      *          {@code false} otherwise.
   442      * @since   JDK1.1
   443      */
   444     public boolean isArray() {
   445         return hasProperty(this, "array"); // NOI18N
   446     }
   447 
   448 
   449     /**
   450      * Determines if the specified {@code Class} object represents a
   451      * primitive type.
   452      *
   453      * <p> There are nine predefined {@code Class} objects to represent
   454      * the eight primitive types and void.  These are created by the Java
   455      * Virtual Machine, and have the same names as the primitive types that
   456      * they represent, namely {@code boolean}, {@code byte},
   457      * {@code char}, {@code short}, {@code int},
   458      * {@code long}, {@code float}, and {@code double}.
   459      *
   460      * <p> These objects may only be accessed via the following public static
   461      * final variables, and are the only {@code Class} objects for which
   462      * this method returns {@code true}.
   463      *
   464      * @return true if and only if this class represents a primitive type
   465      *
   466      * @see     java.lang.Boolean#TYPE
   467      * @see     java.lang.Character#TYPE
   468      * @see     java.lang.Byte#TYPE
   469      * @see     java.lang.Short#TYPE
   470      * @see     java.lang.Integer#TYPE
   471      * @see     java.lang.Long#TYPE
   472      * @see     java.lang.Float#TYPE
   473      * @see     java.lang.Double#TYPE
   474      * @see     java.lang.Void#TYPE
   475      * @since JDK1.1
   476      */
   477     @JavaScriptBody(args = {}, body = 
   478            "if (this.primitive) return true;"
   479         + "else return false;"
   480     )
   481     public native boolean isPrimitive();
   482 
   483     /**
   484      * Returns true if this {@code Class} object represents an annotation
   485      * type.  Note that if this method returns true, {@link #isInterface()}
   486      * would also return true, as all annotation types are also interfaces.
   487      *
   488      * @return {@code true} if this class object represents an annotation
   489      *      type; {@code false} otherwise
   490      * @since 1.5
   491      */
   492     public boolean isAnnotation() {
   493         return (getModifiers() & ANNOTATION) != 0;
   494     }
   495 
   496     /**
   497      * Returns {@code true} if this class is a synthetic class;
   498      * returns {@code false} otherwise.
   499      * @return {@code true} if and only if this class is a synthetic class as
   500      *         defined by the Java Language Specification.
   501      * @since 1.5
   502      */
   503     public boolean isSynthetic() {
   504         return (getModifiers() & SYNTHETIC) != 0;
   505     }
   506 
   507     /**
   508      * Returns the  name of the entity (class, interface, array class,
   509      * primitive type, or void) represented by this {@code Class} object,
   510      * as a {@code String}.
   511      *
   512      * <p> If this class object represents a reference type that is not an
   513      * array type then the binary name of the class is returned, as specified
   514      * by
   515      * <cite>The Java&trade; Language Specification</cite>.
   516      *
   517      * <p> If this class object represents a primitive type or void, then the
   518      * name returned is a {@code String} equal to the Java language
   519      * keyword corresponding to the primitive type or void.
   520      *
   521      * <p> If this class object represents a class of arrays, then the internal
   522      * form of the name consists of the name of the element type preceded by
   523      * one or more '{@code [}' characters representing the depth of the array
   524      * nesting.  The encoding of element type names is as follows:
   525      *
   526      * <blockquote><table summary="Element types and encodings">
   527      * <tr><th> Element Type <th> &nbsp;&nbsp;&nbsp; <th> Encoding
   528      * <tr><td> boolean      <td> &nbsp;&nbsp;&nbsp; <td align=center> Z
   529      * <tr><td> byte         <td> &nbsp;&nbsp;&nbsp; <td align=center> B
   530      * <tr><td> char         <td> &nbsp;&nbsp;&nbsp; <td align=center> C
   531      * <tr><td> class or interface
   532      *                       <td> &nbsp;&nbsp;&nbsp; <td align=center> L<i>classname</i>;
   533      * <tr><td> double       <td> &nbsp;&nbsp;&nbsp; <td align=center> D
   534      * <tr><td> float        <td> &nbsp;&nbsp;&nbsp; <td align=center> F
   535      * <tr><td> int          <td> &nbsp;&nbsp;&nbsp; <td align=center> I
   536      * <tr><td> long         <td> &nbsp;&nbsp;&nbsp; <td align=center> J
   537      * <tr><td> short        <td> &nbsp;&nbsp;&nbsp; <td align=center> S
   538      * </table></blockquote>
   539      *
   540      * <p> The class or interface name <i>classname</i> is the binary name of
   541      * the class specified above.
   542      *
   543      * <p> Examples:
   544      * <blockquote><pre>
   545      * String.class.getName()
   546      *     returns "java.lang.String"
   547      * byte.class.getName()
   548      *     returns "byte"
   549      * (new Object[3]).getClass().getName()
   550      *     returns "[Ljava.lang.Object;"
   551      * (new int[3][4][5][6][7][8][9]).getClass().getName()
   552      *     returns "[[[[[[[I"
   553      * </pre></blockquote>
   554      *
   555      * @return  the name of the class or interface
   556      *          represented by this object.
   557      */
   558     public String getName() {
   559         return jvmName().replace('/', '.');
   560     }
   561 
   562     @JavaScriptBody(args = {}, body = "return this.jvmName;")
   563     private native String jvmName();
   564 
   565     
   566     /**
   567      * Returns an array of {@code TypeVariable} objects that represent the
   568      * type variables declared by the generic declaration represented by this
   569      * {@code GenericDeclaration} object, in declaration order.  Returns an
   570      * array of length 0 if the underlying generic declaration declares no type
   571      * variables.
   572      *
   573      * @return an array of {@code TypeVariable} objects that represent
   574      *     the type variables declared by this generic declaration
   575      * @throws java.lang.reflect.GenericSignatureFormatError if the generic
   576      *     signature of this generic declaration does not conform to
   577      *     the format specified in
   578      *     <cite>The Java&trade; Virtual Machine Specification</cite>
   579      * @since 1.5
   580      */
   581     public TypeVariable<Class<T>>[] getTypeParameters() {
   582         throw new UnsupportedOperationException();
   583     }
   584  
   585     /**
   586      * Returns the {@code Class} representing the superclass of the entity
   587      * (class, interface, primitive type or void) represented by this
   588      * {@code Class}.  If this {@code Class} represents either the
   589      * {@code Object} class, an interface, a primitive type, or void, then
   590      * null is returned.  If this object represents an array class then the
   591      * {@code Class} object representing the {@code Object} class is
   592      * returned.
   593      *
   594      * @return the superclass of the class represented by this object.
   595      */
   596     @JavaScriptBody(args = {}, body = "return this.superclass;")
   597     public native Class<? super T> getSuperclass();
   598 
   599     /**
   600      * Returns the Java language modifiers for this class or interface, encoded
   601      * in an integer. The modifiers consist of the Java Virtual Machine's
   602      * constants for {@code public}, {@code protected},
   603      * {@code private}, {@code final}, {@code static},
   604      * {@code abstract} and {@code interface}; they should be decoded
   605      * using the methods of class {@code Modifier}.
   606      *
   607      * <p> If the underlying class is an array class, then its
   608      * {@code public}, {@code private} and {@code protected}
   609      * modifiers are the same as those of its component type.  If this
   610      * {@code Class} represents a primitive type or void, its
   611      * {@code public} modifier is always {@code true}, and its
   612      * {@code protected} and {@code private} modifiers are always
   613      * {@code false}. If this object represents an array class, a
   614      * primitive type or void, then its {@code final} modifier is always
   615      * {@code true} and its interface modifier is always
   616      * {@code false}. The values of its other modifiers are not determined
   617      * by this specification.
   618      *
   619      * <p> The modifier encodings are defined in <em>The Java Virtual Machine
   620      * Specification</em>, table 4.1.
   621      *
   622      * @return the {@code int} representing the modifiers for this class
   623      * @see     java.lang.reflect.Modifier
   624      * @since JDK1.1
   625      */
   626     public int getModifiers() {
   627         return getAccess();
   628     }
   629 
   630 
   631     /**
   632      * Returns the simple name of the underlying class as given in the
   633      * source code. Returns an empty string if the underlying class is
   634      * anonymous.
   635      *
   636      * <p>The simple name of an array is the simple name of the
   637      * component type with "[]" appended.  In particular the simple
   638      * name of an array whose component type is anonymous is "[]".
   639      *
   640      * @return the simple name of the underlying class
   641      * @since 1.5
   642      */
   643     public String getSimpleName() {
   644         if (isArray())
   645             return getComponentType().getSimpleName()+"[]";
   646 
   647         String simpleName = getSimpleBinaryName();
   648         if (simpleName == null) { // top level class
   649             simpleName = getName();
   650             return simpleName.substring(simpleName.lastIndexOf(".")+1); // strip the package name
   651         }
   652         // According to JLS3 "Binary Compatibility" (13.1) the binary
   653         // name of non-package classes (not top level) is the binary
   654         // name of the immediately enclosing class followed by a '$' followed by:
   655         // (for nested and inner classes): the simple name.
   656         // (for local classes): 1 or more digits followed by the simple name.
   657         // (for anonymous classes): 1 or more digits.
   658 
   659         // Since getSimpleBinaryName() will strip the binary name of
   660         // the immediatly enclosing class, we are now looking at a
   661         // string that matches the regular expression "\$[0-9]*"
   662         // followed by a simple name (considering the simple of an
   663         // anonymous class to be the empty string).
   664 
   665         // Remove leading "\$[0-9]*" from the name
   666         int length = simpleName.length();
   667         if (length < 1 || simpleName.charAt(0) != '$')
   668             throw new IllegalStateException("Malformed class name");
   669         int index = 1;
   670         while (index < length && isAsciiDigit(simpleName.charAt(index)))
   671             index++;
   672         // Eventually, this is the empty string iff this is an anonymous class
   673         return simpleName.substring(index);
   674     }
   675 
   676     /**
   677      * Returns the "simple binary name" of the underlying class, i.e.,
   678      * the binary name without the leading enclosing class name.
   679      * Returns {@code null} if the underlying class is a top level
   680      * class.
   681      */
   682     private String getSimpleBinaryName() {
   683         Class<?> enclosingClass = null; // XXX getEnclosingClass();
   684         if (enclosingClass == null) // top level class
   685             return null;
   686         // Otherwise, strip the enclosing class' name
   687         try {
   688             return getName().substring(enclosingClass.getName().length());
   689         } catch (IndexOutOfBoundsException ex) {
   690             throw new IllegalStateException("Malformed class name");
   691         }
   692     }
   693 
   694     /**
   695      * Returns an array containing {@code Field} objects reflecting all
   696      * the accessible public fields of the class or interface represented by
   697      * this {@code Class} object.  The elements in the array returned are
   698      * not sorted and are not in any particular order.  This method returns an
   699      * array of length 0 if the class or interface has no accessible public
   700      * fields, or if it represents an array class, a primitive type, or void.
   701      *
   702      * <p> Specifically, if this {@code Class} object represents a class,
   703      * this method returns the public fields of this class and of all its
   704      * superclasses.  If this {@code Class} object represents an
   705      * interface, this method returns the fields of this interface and of all
   706      * its superinterfaces.
   707      *
   708      * <p> The implicit length field for array class is not reflected by this
   709      * method. User code should use the methods of class {@code Array} to
   710      * manipulate arrays.
   711      *
   712      * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3.
   713      *
   714      * @return the array of {@code Field} objects representing the
   715      * public fields
   716      * @exception  SecurityException
   717      *             If a security manager, <i>s</i>, is present and any of the
   718      *             following conditions is met:
   719      *
   720      *             <ul>
   721      *
   722      *             <li> invocation of
   723      *             {@link SecurityManager#checkMemberAccess
   724      *             s.checkMemberAccess(this, Member.PUBLIC)} denies
   725      *             access to the fields within this class
   726      *
   727      *             <li> the caller's class loader is not the same as or an
   728      *             ancestor of the class loader for the current class and
   729      *             invocation of {@link SecurityManager#checkPackageAccess
   730      *             s.checkPackageAccess()} denies access to the package
   731      *             of this class
   732      *
   733      *             </ul>
   734      *
   735      * @since JDK1.1
   736      */
   737     public Field[] getFields() throws SecurityException {
   738         throw new SecurityException();
   739     }
   740 
   741     /**
   742      * Returns an array containing {@code Method} objects reflecting all
   743      * the public <em>member</em> methods of the class or interface represented
   744      * by this {@code Class} object, including those declared by the class
   745      * or interface and those inherited from superclasses and
   746      * superinterfaces.  Array classes return all the (public) member methods
   747      * inherited from the {@code Object} class.  The elements in the array
   748      * returned are not sorted and are not in any particular order.  This
   749      * method returns an array of length 0 if this {@code Class} object
   750      * represents a class or interface that has no public member methods, or if
   751      * this {@code Class} object represents a primitive type or void.
   752      *
   753      * <p> The class initialization method {@code <clinit>} is not
   754      * included in the returned array. If the class declares multiple public
   755      * member methods with the same parameter types, they are all included in
   756      * the returned array.
   757      *
   758      * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.4.
   759      *
   760      * @return the array of {@code Method} objects representing the
   761      * public methods of this class
   762      * @exception  SecurityException
   763      *             If a security manager, <i>s</i>, is present and any of the
   764      *             following conditions is met:
   765      *
   766      *             <ul>
   767      *
   768      *             <li> invocation of
   769      *             {@link SecurityManager#checkMemberAccess
   770      *             s.checkMemberAccess(this, Member.PUBLIC)} denies
   771      *             access to the methods within this class
   772      *
   773      *             <li> the caller's class loader is not the same as or an
   774      *             ancestor of the class loader for the current class and
   775      *             invocation of {@link SecurityManager#checkPackageAccess
   776      *             s.checkPackageAccess()} denies access to the package
   777      *             of this class
   778      *
   779      *             </ul>
   780      *
   781      * @since JDK1.1
   782      */
   783     public Method[] getMethods() throws SecurityException {
   784         return MethodImpl.findMethods(this, 0x01);
   785     }
   786 
   787     /**
   788      * Returns a {@code Field} object that reflects the specified public
   789      * member field of the class or interface represented by this
   790      * {@code Class} object. The {@code name} parameter is a
   791      * {@code String} specifying the simple name of the desired field.
   792      *
   793      * <p> The field to be reflected is determined by the algorithm that
   794      * follows.  Let C be the class represented by this object:
   795      * <OL>
   796      * <LI> If C declares a public field with the name specified, that is the
   797      *      field to be reflected.</LI>
   798      * <LI> If no field was found in step 1 above, this algorithm is applied
   799      *      recursively to each direct superinterface of C. The direct
   800      *      superinterfaces are searched in the order they were declared.</LI>
   801      * <LI> If no field was found in steps 1 and 2 above, and C has a
   802      *      superclass S, then this algorithm is invoked recursively upon S.
   803      *      If C has no superclass, then a {@code NoSuchFieldException}
   804      *      is thrown.</LI>
   805      * </OL>
   806      *
   807      * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3.
   808      *
   809      * @param name the field name
   810      * @return  the {@code Field} object of this class specified by
   811      * {@code name}
   812      * @exception NoSuchFieldException if a field with the specified name is
   813      *              not found.
   814      * @exception NullPointerException if {@code name} is {@code null}
   815      * @exception  SecurityException
   816      *             If a security manager, <i>s</i>, is present and any of the
   817      *             following conditions is met:
   818      *
   819      *             <ul>
   820      *
   821      *             <li> invocation of
   822      *             {@link SecurityManager#checkMemberAccess
   823      *             s.checkMemberAccess(this, Member.PUBLIC)} denies
   824      *             access to the field
   825      *
   826      *             <li> the caller's class loader is not the same as or an
   827      *             ancestor of the class loader for the current class and
   828      *             invocation of {@link SecurityManager#checkPackageAccess
   829      *             s.checkPackageAccess()} denies access to the package
   830      *             of this class
   831      *
   832      *             </ul>
   833      *
   834      * @since JDK1.1
   835      */
   836     public Field getField(String name)
   837         throws SecurityException {
   838         throw new SecurityException();
   839     }
   840     
   841     
   842     /**
   843      * Returns a {@code Method} object that reflects the specified public
   844      * member method of the class or interface represented by this
   845      * {@code Class} object. The {@code name} parameter is a
   846      * {@code String} specifying the simple name of the desired method. The
   847      * {@code parameterTypes} parameter is an array of {@code Class}
   848      * objects that identify the method's formal parameter types, in declared
   849      * order. If {@code parameterTypes} is {@code null}, it is
   850      * treated as if it were an empty array.
   851      *
   852      * <p> If the {@code name} is "{@code <init>};"or "{@code <clinit>}" a
   853      * {@code NoSuchMethodException} is raised. Otherwise, the method to
   854      * be reflected is determined by the algorithm that follows.  Let C be the
   855      * class represented by this object:
   856      * <OL>
   857      * <LI> C is searched for any <I>matching methods</I>. If no matching
   858      *      method is found, the algorithm of step 1 is invoked recursively on
   859      *      the superclass of C.</LI>
   860      * <LI> If no method was found in step 1 above, the superinterfaces of C
   861      *      are searched for a matching method. If any such method is found, it
   862      *      is reflected.</LI>
   863      * </OL>
   864      *
   865      * To find a matching method in a class C:&nbsp; If C declares exactly one
   866      * public method with the specified name and exactly the same formal
   867      * parameter types, that is the method reflected. If more than one such
   868      * method is found in C, and one of these methods has a return type that is
   869      * more specific than any of the others, that method is reflected;
   870      * otherwise one of the methods is chosen arbitrarily.
   871      *
   872      * <p>Note that there may be more than one matching method in a
   873      * class because while the Java language forbids a class to
   874      * declare multiple methods with the same signature but different
   875      * return types, the Java virtual machine does not.  This
   876      * increased flexibility in the virtual machine can be used to
   877      * implement various language features.  For example, covariant
   878      * returns can be implemented with {@linkplain
   879      * java.lang.reflect.Method#isBridge bridge methods}; the bridge
   880      * method and the method being overridden would have the same
   881      * signature but different return types.
   882      *
   883      * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.4.
   884      *
   885      * @param name the name of the method
   886      * @param parameterTypes the list of parameters
   887      * @return the {@code Method} object that matches the specified
   888      * {@code name} and {@code parameterTypes}
   889      * @exception NoSuchMethodException if a matching method is not found
   890      *            or if the name is "&lt;init&gt;"or "&lt;clinit&gt;".
   891      * @exception NullPointerException if {@code name} is {@code null}
   892      * @exception  SecurityException
   893      *             If a security manager, <i>s</i>, is present and any of the
   894      *             following conditions is met:
   895      *
   896      *             <ul>
   897      *
   898      *             <li> invocation of
   899      *             {@link SecurityManager#checkMemberAccess
   900      *             s.checkMemberAccess(this, Member.PUBLIC)} denies
   901      *             access to the method
   902      *
   903      *             <li> the caller's class loader is not the same as or an
   904      *             ancestor of the class loader for the current class and
   905      *             invocation of {@link SecurityManager#checkPackageAccess
   906      *             s.checkPackageAccess()} denies access to the package
   907      *             of this class
   908      *
   909      *             </ul>
   910      *
   911      * @since JDK1.1
   912      */
   913     public Method getMethod(String name, Class<?>... parameterTypes)
   914         throws SecurityException, NoSuchMethodException {
   915         Method m = MethodImpl.findMethod(this, name, parameterTypes);
   916         if (m == null) {
   917             StringBuilder sb = new StringBuilder();
   918             sb.append(getName()).append('.').append(name).append('(');
   919             String sep = "";
   920             for (int i = 0; i < parameterTypes.length; i++) {
   921                 sb.append(sep).append(parameterTypes[i].getName());
   922                 sep = ", ";
   923             }
   924             sb.append(')');
   925             throw new NoSuchMethodException(sb.toString());
   926         }
   927         return m;
   928     }
   929     
   930     /**
   931      * Returns an array of {@code Method} objects reflecting all the
   932      * methods declared by the class or interface represented by this
   933      * {@code Class} object. This includes public, protected, default
   934      * (package) access, and private methods, but excludes inherited methods.
   935      * The elements in the array returned are not sorted and are not in any
   936      * particular order.  This method returns an array of length 0 if the class
   937      * or interface declares no methods, or if this {@code Class} object
   938      * represents a primitive type, an array class, or void.  The class
   939      * initialization method {@code <clinit>} is not included in the
   940      * returned array. If the class declares multiple public member methods
   941      * with the same parameter types, they are all included in the returned
   942      * array.
   943      *
   944      * <p> See <em>The Java Language Specification</em>, section 8.2.
   945      *
   946      * @return    the array of {@code Method} objects representing all the
   947      * declared methods of this class
   948      * @exception  SecurityException
   949      *             If a security manager, <i>s</i>, is present and any of the
   950      *             following conditions is met:
   951      *
   952      *             <ul>
   953      *
   954      *             <li> invocation of
   955      *             {@link SecurityManager#checkMemberAccess
   956      *             s.checkMemberAccess(this, Member.DECLARED)} denies
   957      *             access to the declared methods within this class
   958      *
   959      *             <li> the caller's class loader is not the same as or an
   960      *             ancestor of the class loader for the current class and
   961      *             invocation of {@link SecurityManager#checkPackageAccess
   962      *             s.checkPackageAccess()} denies access to the package
   963      *             of this class
   964      *
   965      *             </ul>
   966      *
   967      * @since JDK1.1
   968      */
   969     public Method[] getDeclaredMethods() throws SecurityException {
   970         throw new SecurityException();
   971     }
   972     
   973     /**
   974      * Character.isDigit answers {@code true} to some non-ascii
   975      * digits.  This one does not.
   976      */
   977     private static boolean isAsciiDigit(char c) {
   978         return '0' <= c && c <= '9';
   979     }
   980 
   981     /**
   982      * Returns the canonical name of the underlying class as
   983      * defined by the Java Language Specification.  Returns null if
   984      * the underlying class does not have a canonical name (i.e., if
   985      * it is a local or anonymous class or an array whose component
   986      * type does not have a canonical name).
   987      * @return the canonical name of the underlying class if it exists, and
   988      * {@code null} otherwise.
   989      * @since 1.5
   990      */
   991     public String getCanonicalName() {
   992         if (isArray()) {
   993             String canonicalName = getComponentType().getCanonicalName();
   994             if (canonicalName != null)
   995                 return canonicalName + "[]";
   996             else
   997                 return null;
   998         }
   999 //        if (isLocalOrAnonymousClass())
  1000 //            return null;
  1001 //        Class<?> enclosingClass = getEnclosingClass();
  1002         Class<?> enclosingClass = null;
  1003         if (enclosingClass == null) { // top level class
  1004             return getName();
  1005         } else {
  1006             String enclosingName = enclosingClass.getCanonicalName();
  1007             if (enclosingName == null)
  1008                 return null;
  1009             return enclosingName + "." + getSimpleName();
  1010         }
  1011     }
  1012 
  1013     /**
  1014      * Finds a resource with a given name.  The rules for searching resources
  1015      * associated with a given class are implemented by the defining
  1016      * {@linkplain ClassLoader class loader} of the class.  This method
  1017      * delegates to this object's class loader.  If this object was loaded by
  1018      * the bootstrap class loader, the method delegates to {@link
  1019      * ClassLoader#getSystemResourceAsStream}.
  1020      *
  1021      * <p> Before delegation, an absolute resource name is constructed from the
  1022      * given resource name using this algorithm:
  1023      *
  1024      * <ul>
  1025      *
  1026      * <li> If the {@code name} begins with a {@code '/'}
  1027      * (<tt>'&#92;u002f'</tt>), then the absolute name of the resource is the
  1028      * portion of the {@code name} following the {@code '/'}.
  1029      *
  1030      * <li> Otherwise, the absolute name is of the following form:
  1031      *
  1032      * <blockquote>
  1033      *   {@code modified_package_name/name}
  1034      * </blockquote>
  1035      *
  1036      * <p> Where the {@code modified_package_name} is the package name of this
  1037      * object with {@code '/'} substituted for {@code '.'}
  1038      * (<tt>'&#92;u002e'</tt>).
  1039      *
  1040      * </ul>
  1041      *
  1042      * @param  name name of the desired resource
  1043      * @return      A {@link java.io.InputStream} object or {@code null} if
  1044      *              no resource with this name is found
  1045      * @throws  NullPointerException If {@code name} is {@code null}
  1046      * @since  JDK1.1
  1047      */
  1048      public InputStream getResourceAsStream(String name) {
  1049         name = resolveName(name);
  1050         byte[] arr = getResourceAsStream0(name);
  1051         return arr == null ? null : new ByteArrayInputStream(arr);
  1052      }
  1053      
  1054      @JavaScriptBody(args = "name", body = 
  1055          "return (vm.loadBytes) ? vm.loadBytes(name) : null;"
  1056      )
  1057      private static native byte[] getResourceAsStream0(String name);
  1058 
  1059     /**
  1060      * Finds a resource with a given name.  The rules for searching resources
  1061      * associated with a given class are implemented by the defining
  1062      * {@linkplain ClassLoader class loader} of the class.  This method
  1063      * delegates to this object's class loader.  If this object was loaded by
  1064      * the bootstrap class loader, the method delegates to {@link
  1065      * ClassLoader#getSystemResource}.
  1066      *
  1067      * <p> Before delegation, an absolute resource name is constructed from the
  1068      * given resource name using this algorithm:
  1069      *
  1070      * <ul>
  1071      *
  1072      * <li> If the {@code name} begins with a {@code '/'}
  1073      * (<tt>'&#92;u002f'</tt>), then the absolute name of the resource is the
  1074      * portion of the {@code name} following the {@code '/'}.
  1075      *
  1076      * <li> Otherwise, the absolute name is of the following form:
  1077      *
  1078      * <blockquote>
  1079      *   {@code modified_package_name/name}
  1080      * </blockquote>
  1081      *
  1082      * <p> Where the {@code modified_package_name} is the package name of this
  1083      * object with {@code '/'} substituted for {@code '.'}
  1084      * (<tt>'&#92;u002e'</tt>).
  1085      *
  1086      * </ul>
  1087      *
  1088      * @param  name name of the desired resource
  1089      * @return      A  {@link java.net.URL} object or {@code null} if no
  1090      *              resource with this name is found
  1091      * @since  JDK1.1
  1092      */
  1093     public java.net.URL getResource(String name) {
  1094         InputStream is = getResourceAsStream(name);
  1095         return is == null ? null : newResourceURL(URL.class, "res:/" + name, is);
  1096     }
  1097     
  1098     @JavaScriptBody(args = { "url", "spec", "is" }, body = 
  1099         "var u = url.cnstr(true);\n"
  1100       + "u.constructor.cons__VLjava_lang_String_2Ljava_io_InputStream_2.call(u, spec, is);\n"
  1101       + "return u;"
  1102     )
  1103     private static native URL newResourceURL(Class<URL> url, String spec, InputStream is);
  1104 
  1105    /**
  1106      * Add a package name prefix if the name is not absolute Remove leading "/"
  1107      * if name is absolute
  1108      */
  1109     private String resolveName(String name) {
  1110         if (name == null) {
  1111             return name;
  1112         }
  1113         if (!name.startsWith("/")) {
  1114             Class<?> c = this;
  1115             while (c.isArray()) {
  1116                 c = c.getComponentType();
  1117             }
  1118             String baseName = c.getName();
  1119             int index = baseName.lastIndexOf('.');
  1120             if (index != -1) {
  1121                 name = baseName.substring(0, index).replace('.', '/')
  1122                     +"/"+name;
  1123             }
  1124         } else {
  1125             name = name.substring(1);
  1126         }
  1127         return name;
  1128     }
  1129     
  1130     /**
  1131      * Returns the class loader for the class.  Some implementations may use
  1132      * null to represent the bootstrap class loader. This method will return
  1133      * null in such implementations if this class was loaded by the bootstrap
  1134      * class loader.
  1135      *
  1136      * <p> If a security manager is present, and the caller's class loader is
  1137      * not null and the caller's class loader is not the same as or an ancestor of
  1138      * the class loader for the class whose class loader is requested, then
  1139      * this method calls the security manager's {@code checkPermission}
  1140      * method with a {@code RuntimePermission("getClassLoader")}
  1141      * permission to ensure it's ok to access the class loader for the class.
  1142      *
  1143      * <p>If this object
  1144      * represents a primitive type or void, null is returned.
  1145      *
  1146      * @return  the class loader that loaded the class or interface
  1147      *          represented by this object.
  1148      * @throws SecurityException
  1149      *    if a security manager exists and its
  1150      *    {@code checkPermission} method denies
  1151      *    access to the class loader for the class.
  1152      * @see java.lang.ClassLoader
  1153      * @see SecurityManager#checkPermission
  1154      * @see java.lang.RuntimePermission
  1155      */
  1156     public ClassLoader getClassLoader() {
  1157         throw new SecurityException();
  1158     }
  1159 
  1160     /**
  1161      * Determines the interfaces implemented by the class or interface
  1162      * represented by this object.
  1163      *
  1164      * <p> If this object represents a class, the return value is an array
  1165      * containing objects representing all interfaces implemented by the
  1166      * class. The order of the interface objects in the array corresponds to
  1167      * the order of the interface names in the {@code implements} clause
  1168      * of the declaration of the class represented by this object. For
  1169      * example, given the declaration:
  1170      * <blockquote>
  1171      * {@code class Shimmer implements FloorWax, DessertTopping { ... }}
  1172      * </blockquote>
  1173      * suppose the value of {@code s} is an instance of
  1174      * {@code Shimmer}; the value of the expression:
  1175      * <blockquote>
  1176      * {@code s.getClass().getInterfaces()[0]}
  1177      * </blockquote>
  1178      * is the {@code Class} object that represents interface
  1179      * {@code FloorWax}; and the value of:
  1180      * <blockquote>
  1181      * {@code s.getClass().getInterfaces()[1]}
  1182      * </blockquote>
  1183      * is the {@code Class} object that represents interface
  1184      * {@code DessertTopping}.
  1185      *
  1186      * <p> If this object represents an interface, the array contains objects
  1187      * representing all interfaces extended by the interface. The order of the
  1188      * interface objects in the array corresponds to the order of the interface
  1189      * names in the {@code extends} clause of the declaration of the
  1190      * interface represented by this object.
  1191      *
  1192      * <p> If this object represents a class or interface that implements no
  1193      * interfaces, the method returns an array of length 0.
  1194      *
  1195      * <p> If this object represents a primitive type or void, the method
  1196      * returns an array of length 0.
  1197      *
  1198      * @return an array of interfaces implemented by this class.
  1199      */
  1200     public native Class<?>[] getInterfaces();
  1201     
  1202     /**
  1203      * Returns the {@code Class} representing the component type of an
  1204      * array.  If this class does not represent an array class this method
  1205      * returns null.
  1206      *
  1207      * @return the {@code Class} representing the component type of this
  1208      * class if this class is an array
  1209      * @see     java.lang.reflect.Array
  1210      * @since JDK1.1
  1211      */
  1212     public Class<?> getComponentType() {
  1213         if (isArray()) {
  1214             try {
  1215                 return getComponentType0();
  1216             } catch (ClassNotFoundException cnfe) {
  1217                 throw new IllegalStateException(cnfe);
  1218             }
  1219         }
  1220         return null;
  1221     }
  1222 
  1223     private Class<?> getComponentType0() throws ClassNotFoundException {
  1224         String n = getName().substring(1);
  1225         switch (n.charAt(0)) {
  1226             case 'L': 
  1227                 n = n.substring(1, n.length() - 1);
  1228                 return Class.forName(n);
  1229             case 'I':
  1230                 return Integer.TYPE;
  1231             case 'J':
  1232                 return Long.TYPE;
  1233             case 'D':
  1234                 return Double.TYPE;
  1235             case 'F':
  1236                 return Float.TYPE;
  1237             case 'B':
  1238                 return Byte.TYPE;
  1239             case 'Z':
  1240                 return Boolean.TYPE;
  1241             case 'S':
  1242                 return Short.TYPE;
  1243             case 'V':
  1244                 return Void.TYPE;
  1245             case 'C':
  1246                 return Character.TYPE;
  1247             case '[':
  1248                 return defineArray(n);
  1249             default:
  1250                 throw new ClassNotFoundException("Unknown component type of " + getName());
  1251         }
  1252     }
  1253     
  1254     @JavaScriptBody(args = { "sig" }, body = 
  1255         "var c = Array[sig];\n" +
  1256         "if (c) return c;\n" +
  1257         "c = vm.java_lang_Class(true);\n" +
  1258         "c.jvmName = sig;\n" +
  1259         "c.superclass = vm.java_lang_Object(false).$class;\n" +
  1260         "c.array = true;\n" +
  1261         "Array[sig] = c;\n" +
  1262         "return c;"
  1263     )
  1264     private static native Class<?> defineArray(String sig);
  1265     
  1266     /**
  1267      * Returns true if and only if this class was declared as an enum in the
  1268      * source code.
  1269      *
  1270      * @return true if and only if this class was declared as an enum in the
  1271      *     source code
  1272      * @since 1.5
  1273      */
  1274     public boolean isEnum() {
  1275         // An enum must both directly extend java.lang.Enum and have
  1276         // the ENUM bit set; classes for specialized enum constants
  1277         // don't do the former.
  1278         return (this.getModifiers() & ENUM) != 0 &&
  1279         this.getSuperclass() == java.lang.Enum.class;
  1280     }
  1281 
  1282     /**
  1283      * Casts an object to the class or interface represented
  1284      * by this {@code Class} object.
  1285      *
  1286      * @param obj the object to be cast
  1287      * @return the object after casting, or null if obj is null
  1288      *
  1289      * @throws ClassCastException if the object is not
  1290      * null and is not assignable to the type T.
  1291      *
  1292      * @since 1.5
  1293      */
  1294     public T cast(Object obj) {
  1295         if (obj != null && !isInstance(obj))
  1296             throw new ClassCastException(cannotCastMsg(obj));
  1297         return (T) obj;
  1298     }
  1299 
  1300     private String cannotCastMsg(Object obj) {
  1301         return "Cannot cast " + obj.getClass().getName() + " to " + getName();
  1302     }
  1303 
  1304     /**
  1305      * Casts this {@code Class} object to represent a subclass of the class
  1306      * represented by the specified class object.  Checks that that the cast
  1307      * is valid, and throws a {@code ClassCastException} if it is not.  If
  1308      * this method succeeds, it always returns a reference to this class object.
  1309      *
  1310      * <p>This method is useful when a client needs to "narrow" the type of
  1311      * a {@code Class} object to pass it to an API that restricts the
  1312      * {@code Class} objects that it is willing to accept.  A cast would
  1313      * generate a compile-time warning, as the correctness of the cast
  1314      * could not be checked at runtime (because generic types are implemented
  1315      * by erasure).
  1316      *
  1317      * @return this {@code Class} object, cast to represent a subclass of
  1318      *    the specified class object.
  1319      * @throws ClassCastException if this {@code Class} object does not
  1320      *    represent a subclass of the specified class (here "subclass" includes
  1321      *    the class itself).
  1322      * @since 1.5
  1323      */
  1324     public <U> Class<? extends U> asSubclass(Class<U> clazz) {
  1325         if (clazz.isAssignableFrom(this))
  1326             return (Class<? extends U>) this;
  1327         else
  1328             throw new ClassCastException(this.toString());
  1329     }
  1330 
  1331     @JavaScriptBody(args = { "ac" }, 
  1332         body = 
  1333           "if (this.anno) {"
  1334         + "  return this.anno['L' + ac.jvmName + ';'];"
  1335         + "} else return null;"
  1336     )
  1337     private Object getAnnotationData(Class<?> annotationClass) {
  1338         throw new UnsupportedOperationException();
  1339     }
  1340     /**
  1341      * @throws NullPointerException {@inheritDoc}
  1342      * @since 1.5
  1343      */
  1344     public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {
  1345         Object data = getAnnotationData(annotationClass);
  1346         return data == null ? null : AnnotationImpl.create(annotationClass, data);
  1347     }
  1348 
  1349     /**
  1350      * @throws NullPointerException {@inheritDoc}
  1351      * @since 1.5
  1352      */
  1353     @JavaScriptBody(args = { "ac" }, 
  1354         body = "if (this.anno && this.anno['L' + ac.jvmName + ';']) { return true; }"
  1355         + "else return false;"
  1356     )
  1357     public boolean isAnnotationPresent(
  1358         Class<? extends Annotation> annotationClass) {
  1359         if (annotationClass == null)
  1360             throw new NullPointerException();
  1361 
  1362         return getAnnotation(annotationClass) != null;
  1363     }
  1364 
  1365     @JavaScriptBody(args = {}, body = "return this.anno;")
  1366     private Object getAnnotationData() {
  1367         throw new UnsupportedOperationException();
  1368     }
  1369 
  1370     /**
  1371      * @since 1.5
  1372      */
  1373     public Annotation[] getAnnotations() {
  1374         Object data = getAnnotationData();
  1375         return data == null ? new Annotation[0] : AnnotationImpl.create(data);
  1376     }
  1377 
  1378     /**
  1379      * @since 1.5
  1380      */
  1381     public Annotation[] getDeclaredAnnotations()  {
  1382         throw new UnsupportedOperationException();
  1383     }
  1384 
  1385     @JavaScriptBody(args = "type", body = ""
  1386         + "var c = vm.java_lang_Class(true);"
  1387         + "c.jvmName = type;"
  1388         + "c.primitive = true;"
  1389         + "return c;"
  1390     )
  1391     native static Class getPrimitiveClass(String type);
  1392 
  1393     @JavaScriptBody(args = {}, body = 
  1394         "return vm.desiredAssertionStatus ? vm.desiredAssertionStatus : false;"
  1395     )
  1396     public native boolean desiredAssertionStatus();
  1397 }