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