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