rt/emul/mini/src/main/java/java/lang/Class.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sun, 04 May 2014 12:02:57 +0200
branchclosure
changeset 1522 0d32bf6b4436
parent 1515 d6d1fc565854
child 1528 984f8ed9e514
permissions -rw-r--r--
Exporting widely used methods via Class, which is guaranteed to be available, rather than Throwable
     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 java.io.InputStream;
    30 import java.lang.annotation.Annotation;
    31 import java.lang.reflect.Array;
    32 import java.lang.reflect.Constructor;
    33 import java.lang.reflect.Field;
    34 import java.lang.reflect.Method;
    35 import java.lang.reflect.TypeVariable;
    36 import java.net.URL;
    37 import org.apidesign.bck2brwsr.core.JavaScriptBody;
    38 import org.apidesign.bck2brwsr.core.JavaScriptOnly;
    39 import org.apidesign.bck2brwsr.emul.reflect.AnnotationImpl;
    40 import org.apidesign.bck2brwsr.emul.reflect.MethodImpl;
    41 
    42 /**
    43  * Instances of the class {@code Class} represent classes and
    44  * interfaces in a running Java application.  An enum is a kind of
    45  * class and an annotation is a kind of interface.  Every array also
    46  * belongs to a class that is reflected as a {@code Class} object
    47  * that is shared by all arrays with the same element type and number
    48  * of dimensions.  The primitive Java types ({@code boolean},
    49  * {@code byte}, {@code char}, {@code short},
    50  * {@code int}, {@code long}, {@code float}, and
    51  * {@code double}), and the keyword {@code void} are also
    52  * represented as {@code Class} objects.
    53  *
    54  * <p> {@code Class} has no public constructor. Instead {@code Class}
    55  * objects are constructed automatically by the Java Virtual Machine as classes
    56  * are loaded and by calls to the {@code defineClass} method in the class
    57  * loader.
    58  *
    59  * <p> The following example uses a {@code Class} object to print the
    60  * class name of an object:
    61  *
    62  * <p> <blockquote><pre>
    63  *     void printClassName(Object obj) {
    64  *         System.out.println("The class of " + obj +
    65  *                            " is " + obj.getClass().getName());
    66  *     }
    67  * </pre></blockquote>
    68  *
    69  * <p> It is also possible to get the {@code Class} object for a named
    70  * type (or for void) using a class literal.  See Section 15.8.2 of
    71  * <cite>The Java&trade; Language Specification</cite>.
    72  * For example:
    73  *
    74  * <p> <blockquote>
    75  *     {@code System.out.println("The name of class Foo is: "+Foo.class.getName());}
    76  * </blockquote>
    77  *
    78  * @param <T> the type of the class modeled by this {@code Class}
    79  * object.  For example, the type of {@code String.class} is {@code
    80  * Class<String>}.  Use {@code Class<?>} if the class being modeled is
    81  * unknown.
    82  *
    83  * @author  unascribed
    84  * @see     java.lang.ClassLoader#defineClass(byte[], int, int)
    85  * @since   JDK1.0
    86  */
    87 public final
    88     class Class<T> implements java.io.Serializable,
    89                               java.lang.reflect.GenericDeclaration,
    90                               java.lang.reflect.Type,
    91                               java.lang.reflect.AnnotatedElement {
    92     private static final int ANNOTATION= 0x00002000;
    93     private static final int ENUM      = 0x00004000;
    94     private static final int SYNTHETIC = 0x00001000;
    95 
    96     /*
    97      * Constructor. Only the Java Virtual Machine creates Class
    98      * objects.
    99      */
   100     private Class() {}
   101 
   102 
   103     /**
   104      * Converts the object to a string. The string representation is the
   105      * string "class" or "interface", followed by a space, and then by the
   106      * fully qualified name of the class in the format returned by
   107      * {@code getName}.  If this {@code Class} object represents a
   108      * primitive type, this method returns the name of the primitive type.  If
   109      * this {@code Class} object represents void this method returns
   110      * "void".
   111      *
   112      * @return a string representation of this class object.
   113      */
   114     public String toString() {
   115         return (isInterface() ? "interface " : (isPrimitive() ? "" : "class "))
   116             + getName();
   117     }
   118 
   119 
   120     /**
   121      * Returns the {@code Class} object associated with the class or
   122      * interface with the given string name.  Invoking this method is
   123      * equivalent to:
   124      *
   125      * <blockquote>
   126      *  {@code Class.forName(className, true, currentLoader)}
   127      * </blockquote>
   128      *
   129      * where {@code currentLoader} denotes the defining class loader of
   130      * the current class.
   131      *
   132      * <p> For example, the following code fragment returns the
   133      * runtime {@code Class} descriptor for the class named
   134      * {@code java.lang.Thread}:
   135      *
   136      * <blockquote>
   137      *   {@code Class t = Class.forName("java.lang.Thread")}
   138      * </blockquote>
   139      * <p>
   140      * A call to {@code forName("X")} causes the class named
   141      * {@code X} to be initialized.
   142      *
   143      * @param      className   the fully qualified name of the desired class.
   144      * @return     the {@code Class} object for the class with the
   145      *             specified name.
   146      * @exception LinkageError if the linkage fails
   147      * @exception ExceptionInInitializerError if the initialization provoked
   148      *            by this method fails
   149      * @exception ClassNotFoundException if the class cannot be located
   150      */
   151     public static Class<?> forName(String className)
   152     throws ClassNotFoundException {
   153         if (className.startsWith("[")) {
   154             Class<?> arrType = defineArray(className);
   155             Class<?> c = arrType;
   156             while (c != null && c.isArray()) {
   157                 c = c.getComponentType0(); // verify component type is sane
   158             }
   159             return arrType;
   160         }
   161         try {
   162             Class<?> c = loadCls(className, className.replace('.', '_'));
   163             if (c == null) {
   164                 throw new ClassNotFoundException(className);
   165             }
   166             return c;
   167         } catch (Throwable ex) {
   168             throw new ClassNotFoundException(className, ex);
   169         }
   170     }
   171 
   172 
   173     /**
   174      * Returns the {@code Class} object associated with the class or
   175      * interface with the given string name, using the given class loader.
   176      * Given the fully qualified name for a class or interface (in the same
   177      * format returned by {@code getName}) this method attempts to
   178      * locate, load, and link the class or interface.  The specified class
   179      * loader is used to load the class or interface.  If the parameter
   180      * {@code loader} is null, the class is loaded through the bootstrap
   181      * class loader.  The class is initialized only if the
   182      * {@code initialize} parameter is {@code true} and if it has
   183      * not been initialized earlier.
   184      *
   185      * <p> If {@code name} denotes a primitive type or void, an attempt
   186      * will be made to locate a user-defined class in the unnamed package whose
   187      * name is {@code name}. Therefore, this method cannot be used to
   188      * obtain any of the {@code Class} objects representing primitive
   189      * types or void.
   190      *
   191      * <p> If {@code name} denotes an array class, the component type of
   192      * the array class is loaded but not initialized.
   193      *
   194      * <p> For example, in an instance method the expression:
   195      *
   196      * <blockquote>
   197      *  {@code Class.forName("Foo")}
   198      * </blockquote>
   199      *
   200      * is equivalent to:
   201      *
   202      * <blockquote>
   203      *  {@code Class.forName("Foo", true, this.getClass().getClassLoader())}
   204      * </blockquote>
   205      *
   206      * Note that this method throws errors related to loading, linking or
   207      * initializing as specified in Sections 12.2, 12.3 and 12.4 of <em>The
   208      * Java Language Specification</em>.
   209      * Note that this method does not check whether the requested class
   210      * is accessible to its caller.
   211      *
   212      * <p> If the {@code loader} is {@code null}, and a security
   213      * manager is present, and the caller's class loader is not null, then this
   214      * method calls the security manager's {@code checkPermission} method
   215      * with a {@code RuntimePermission("getClassLoader")} permission to
   216      * ensure it's ok to access the bootstrap class loader.
   217      *
   218      * @param name       fully qualified name of the desired class
   219      * @param initialize whether the class must be initialized
   220      * @param loader     class loader from which the class must be loaded
   221      * @return           class object representing the desired class
   222      *
   223      * @exception LinkageError if the linkage fails
   224      * @exception ExceptionInInitializerError if the initialization provoked
   225      *            by this method fails
   226      * @exception ClassNotFoundException if the class cannot be located by
   227      *            the specified class loader
   228      *
   229      * @see       java.lang.Class#forName(String)
   230      * @see       java.lang.ClassLoader
   231      * @since     1.2
   232      */
   233     public static Class<?> forName(String name, boolean initialize,
   234                                    ClassLoader loader)
   235         throws ClassNotFoundException
   236     {
   237         return forName(name);
   238     }
   239     
   240     @JavaScriptBody(args = {"n", "c" }, body =
   241         "if (!vm[c]) {\n"
   242       + "  if (vm.loadClass) {\n"
   243       + "    vm.loadClass(n);\n"
   244       + "  }\n"
   245       + "  if (!vm[c]) return null;\n"
   246       + "}\n"
   247       + "vm[c](false);"
   248       + "return vm[c].$class;"
   249     )
   250     private static native Class<?> loadCls(String n, String c);
   251 
   252 
   253     /**
   254      * Creates a new instance of the class represented by this {@code Class}
   255      * object.  The class is instantiated as if by a {@code new}
   256      * expression with an empty argument list.  The class is initialized if it
   257      * has not already been initialized.
   258      *
   259      * <p>Note that this method propagates any exception thrown by the
   260      * nullary constructor, including a checked exception.  Use of
   261      * this method effectively bypasses the compile-time exception
   262      * checking that would otherwise be performed by the compiler.
   263      * The {@link
   264      * java.lang.reflect.Constructor#newInstance(java.lang.Object...)
   265      * Constructor.newInstance} method avoids this problem by wrapping
   266      * any exception thrown by the constructor in a (checked) {@link
   267      * java.lang.reflect.InvocationTargetException}.
   268      *
   269      * @return     a newly allocated instance of the class represented by this
   270      *             object.
   271      * @exception  IllegalAccessException  if the class or its nullary
   272      *               constructor is not accessible.
   273      * @exception  InstantiationException
   274      *               if this {@code Class} represents an abstract class,
   275      *               an interface, an array class, a primitive type, or void;
   276      *               or if the class has no nullary constructor;
   277      *               or if the instantiation fails for some other reason.
   278      * @exception  ExceptionInInitializerError if the initialization
   279      *               provoked by this method fails.
   280      * @exception  SecurityException
   281      *             If a security manager, <i>s</i>, is present and any of the
   282      *             following conditions is met:
   283      *
   284      *             <ul>
   285      *
   286      *             <li> invocation of
   287      *             {@link SecurityManager#checkMemberAccess
   288      *             s.checkMemberAccess(this, Member.PUBLIC)} denies
   289      *             creation of new instances of this class
   290      *
   291      *             <li> the caller's class loader is not the same as or an
   292      *             ancestor of the class loader for the current class and
   293      *             invocation of {@link SecurityManager#checkPackageAccess
   294      *             s.checkPackageAccess()} denies access to the package
   295      *             of this class
   296      *
   297      *             </ul>
   298      *
   299      */
   300     @JavaScriptBody(args = { "self", "illegal" }, body =
   301           "\nvar c = self.cnstr;"
   302         + "\nif (c['cons__V']) {"
   303         + "\n  if ((c.cons__V.access & 0x1) != 0) {"
   304         + "\n    var inst = c();"
   305         + "\n    c.cons__V.call(inst);"
   306         + "\n    return inst;"
   307         + "\n  }"
   308         + "\n  return illegal;"
   309         + "\n}"
   310         + "\nreturn null;"
   311     )
   312     private static native Object newInstance0(Class<?> self, Object illegal);
   313     
   314     public T newInstance()
   315         throws InstantiationException, IllegalAccessException
   316     {
   317         Object illegal = new Object();
   318         Object inst = newInstance0(this, illegal);
   319         if (inst == null) {
   320             throw new InstantiationException(getName());
   321         }
   322         if (inst == illegal) {
   323             throw new IllegalAccessException();
   324         }
   325         return (T)inst;
   326     }
   327 
   328     /**
   329      * Determines if the specified {@code Object} is assignment-compatible
   330      * with the object represented by this {@code Class}.  This method is
   331      * the dynamic equivalent of the Java language {@code instanceof}
   332      * operator. The method returns {@code true} if the specified
   333      * {@code Object} argument is non-null and can be cast to the
   334      * reference type represented by this {@code Class} object without
   335      * raising a {@code ClassCastException.} It returns {@code false}
   336      * otherwise.
   337      *
   338      * <p> Specifically, if this {@code Class} object represents a
   339      * declared class, this method returns {@code true} if the specified
   340      * {@code Object} argument is an instance of the represented class (or
   341      * of any of its subclasses); it returns {@code false} otherwise. If
   342      * this {@code Class} object represents an array class, this method
   343      * returns {@code true} if the specified {@code Object} argument
   344      * can be converted to an object of the array class by an identity
   345      * conversion or by a widening reference conversion; it returns
   346      * {@code false} otherwise. If this {@code Class} object
   347      * represents an interface, this method returns {@code true} if the
   348      * class or any superclass of the specified {@code Object} argument
   349      * implements this interface; it returns {@code false} otherwise. If
   350      * this {@code Class} object represents a primitive type, this method
   351      * returns {@code false}.
   352      *
   353      * @param   obj the object to check
   354      * @return  true if {@code obj} is an instance of this class
   355      *
   356      * @since JDK1.1
   357      */
   358     public boolean isInstance(Object obj) {
   359         if (obj == null) {
   360             return false;
   361         }
   362         if (isArray()) {
   363             return isAssignableFrom(obj.getClass());
   364         }
   365         
   366         String prop = "$instOf_" + getName().replace('.', '_');
   367         return hasProperty(obj, prop);
   368     }
   369     
   370     @JavaScriptBody(args = { "who", "prop" }, body = 
   371         "if (who[prop]) return true; else return false;"
   372     )
   373     private static native boolean hasProperty(Object who, String prop);
   374 
   375 
   376     /**
   377      * Determines if the class or interface represented by this
   378      * {@code Class} object is either the same as, or is a superclass or
   379      * superinterface of, the class or interface represented by the specified
   380      * {@code Class} parameter. It returns {@code true} if so;
   381      * otherwise it returns {@code false}. If this {@code Class}
   382      * object represents a primitive type, this method returns
   383      * {@code true} if the specified {@code Class} parameter is
   384      * exactly this {@code Class} object; otherwise it returns
   385      * {@code false}.
   386      *
   387      * <p> Specifically, this method tests whether the type represented by the
   388      * specified {@code Class} parameter can be converted to the type
   389      * represented by this {@code Class} object via an identity conversion
   390      * or via a widening reference conversion. See <em>The Java Language
   391      * Specification</em>, sections 5.1.1 and 5.1.4 , for details.
   392      *
   393      * @param cls the {@code Class} object to be checked
   394      * @return the {@code boolean} value indicating whether objects of the
   395      * type {@code cls} can be assigned to objects of this class
   396      * @exception NullPointerException if the specified Class parameter is
   397      *            null.
   398      * @since JDK1.1
   399      */
   400     public boolean isAssignableFrom(Class<?> cls) {
   401         if (this == cls) {
   402             return true;
   403         }
   404         
   405         if (isArray()) {
   406             final Class<?> cmpType = cls.getComponentType();
   407             if (isPrimitive()) {
   408                 return this == cmpType;
   409             }
   410             return cmpType != null && getComponentType().isAssignableFrom(cmpType);
   411         }
   412         if (isPrimitive()) {
   413             return false;
   414         } else {
   415             if (cls.isPrimitive()) {
   416                 return false;
   417             }
   418             String prop = "$instOf_" + getName().replace('.', '_');
   419             return hasCnstrProperty(cls, prop);
   420         }
   421     }
   422 
   423     @JavaScriptBody(args = { "who", "prop" }, body = 
   424         "if (who.cnstr.prototype[prop]) return true; else return false;"
   425     )
   426     private static native boolean hasCnstrProperty(Object who, String prop);
   427     
   428     
   429     /**
   430      * Determines if the specified {@code Class} object represents an
   431      * interface type.
   432      *
   433      * @return  {@code true} if this object represents an interface;
   434      *          {@code false} otherwise.
   435      */
   436     public boolean isInterface() {
   437         return (getAccess() & 0x200) != 0;
   438     }
   439     
   440     @JavaScriptBody(args = {}, body = "return this.access;")
   441     private native int getAccess();
   442 
   443 
   444     /**
   445      * Determines if this {@code Class} object represents an array class.
   446      *
   447      * @return  {@code true} if this object represents an array class;
   448      *          {@code false} otherwise.
   449      * @since   JDK1.1
   450      */
   451     public boolean isArray() {
   452         return hasProperty(this, "array"); // NOI18N
   453     }
   454 
   455 
   456     /**
   457      * Determines if the specified {@code Class} object represents a
   458      * primitive type.
   459      *
   460      * <p> There are nine predefined {@code Class} objects to represent
   461      * the eight primitive types and void.  These are created by the Java
   462      * Virtual Machine, and have the same names as the primitive types that
   463      * they represent, namely {@code boolean}, {@code byte},
   464      * {@code char}, {@code short}, {@code int},
   465      * {@code long}, {@code float}, and {@code double}.
   466      *
   467      * <p> These objects may only be accessed via the following public static
   468      * final variables, and are the only {@code Class} objects for which
   469      * this method returns {@code true}.
   470      *
   471      * @return true if and only if this class represents a primitive type
   472      *
   473      * @see     java.lang.Boolean#TYPE
   474      * @see     java.lang.Character#TYPE
   475      * @see     java.lang.Byte#TYPE
   476      * @see     java.lang.Short#TYPE
   477      * @see     java.lang.Integer#TYPE
   478      * @see     java.lang.Long#TYPE
   479      * @see     java.lang.Float#TYPE
   480      * @see     java.lang.Double#TYPE
   481      * @see     java.lang.Void#TYPE
   482      * @since JDK1.1
   483      */
   484     @JavaScriptBody(args = {}, body = 
   485            "if (this.primitive) return true;"
   486         + "else return false;"
   487     )
   488     public native boolean isPrimitive();
   489 
   490     /**
   491      * Returns true if this {@code Class} object represents an annotation
   492      * type.  Note that if this method returns true, {@link #isInterface()}
   493      * would also return true, as all annotation types are also interfaces.
   494      *
   495      * @return {@code true} if this class object represents an annotation
   496      *      type; {@code false} otherwise
   497      * @since 1.5
   498      */
   499     public boolean isAnnotation() {
   500         return (getModifiers() & ANNOTATION) != 0;
   501     }
   502 
   503     /**
   504      * Returns {@code true} if this class is a synthetic class;
   505      * returns {@code false} otherwise.
   506      * @return {@code true} if and only if this class is a synthetic class as
   507      *         defined by the Java Language Specification.
   508      * @since 1.5
   509      */
   510     public boolean isSynthetic() {
   511         return (getModifiers() & SYNTHETIC) != 0;
   512     }
   513 
   514     /**
   515      * Returns the  name of the entity (class, interface, array class,
   516      * primitive type, or void) represented by this {@code Class} object,
   517      * as a {@code String}.
   518      *
   519      * <p> If this class object represents a reference type that is not an
   520      * array type then the binary name of the class is returned, as specified
   521      * by
   522      * <cite>The Java&trade; Language Specification</cite>.
   523      *
   524      * <p> If this class object represents a primitive type or void, then the
   525      * name returned is a {@code String} equal to the Java language
   526      * keyword corresponding to the primitive type or void.
   527      *
   528      * <p> If this class object represents a class of arrays, then the internal
   529      * form of the name consists of the name of the element type preceded by
   530      * one or more '{@code [}' characters representing the depth of the array
   531      * nesting.  The encoding of element type names is as follows:
   532      *
   533      * <blockquote><table summary="Element types and encodings">
   534      * <tr><th> Element Type <th> &nbsp;&nbsp;&nbsp; <th> Encoding
   535      * <tr><td> boolean      <td> &nbsp;&nbsp;&nbsp; <td align=center> Z
   536      * <tr><td> byte         <td> &nbsp;&nbsp;&nbsp; <td align=center> B
   537      * <tr><td> char         <td> &nbsp;&nbsp;&nbsp; <td align=center> C
   538      * <tr><td> class or interface
   539      *                       <td> &nbsp;&nbsp;&nbsp; <td align=center> L<i>classname</i>;
   540      * <tr><td> double       <td> &nbsp;&nbsp;&nbsp; <td align=center> D
   541      * <tr><td> float        <td> &nbsp;&nbsp;&nbsp; <td align=center> F
   542      * <tr><td> int          <td> &nbsp;&nbsp;&nbsp; <td align=center> I
   543      * <tr><td> long         <td> &nbsp;&nbsp;&nbsp; <td align=center> J
   544      * <tr><td> short        <td> &nbsp;&nbsp;&nbsp; <td align=center> S
   545      * </table></blockquote>
   546      *
   547      * <p> The class or interface name <i>classname</i> is the binary name of
   548      * the class specified above.
   549      *
   550      * <p> Examples:
   551      * <blockquote><pre>
   552      * String.class.getName()
   553      *     returns "java.lang.String"
   554      * byte.class.getName()
   555      *     returns "byte"
   556      * (new Object[3]).getClass().getName()
   557      *     returns "[Ljava.lang.Object;"
   558      * (new int[3][4][5][6][7][8][9]).getClass().getName()
   559      *     returns "[[[[[[[I"
   560      * </pre></blockquote>
   561      *
   562      * @return  the name of the class or interface
   563      *          represented by this object.
   564      */
   565     public String getName() {
   566         return jvmName().replace('/', '.');
   567     }
   568 
   569     @JavaScriptBody(args = {}, body = "return this.jvmName;")
   570     private native String jvmName();
   571 
   572     
   573     /**
   574      * Returns an array of {@code TypeVariable} objects that represent the
   575      * type variables declared by the generic declaration represented by this
   576      * {@code GenericDeclaration} object, in declaration order.  Returns an
   577      * array of length 0 if the underlying generic declaration declares no type
   578      * variables.
   579      *
   580      * @return an array of {@code TypeVariable} objects that represent
   581      *     the type variables declared by this generic declaration
   582      * @throws java.lang.reflect.GenericSignatureFormatError if the generic
   583      *     signature of this generic declaration does not conform to
   584      *     the format specified in
   585      *     <cite>The Java&trade; Virtual Machine Specification</cite>
   586      * @since 1.5
   587      */
   588     public TypeVariable<Class<T>>[] getTypeParameters() {
   589         throw new UnsupportedOperationException();
   590     }
   591  
   592     /**
   593      * Returns the {@code Class} representing the superclass of the entity
   594      * (class, interface, primitive type or void) represented by this
   595      * {@code Class}.  If this {@code Class} represents either the
   596      * {@code Object} class, an interface, a primitive type, or void, then
   597      * null is returned.  If this object represents an array class then the
   598      * {@code Class} object representing the {@code Object} class is
   599      * returned.
   600      *
   601      * @return the superclass of the class represented by this object.
   602      */
   603     @JavaScriptBody(args = {}, body = "return this.superclass;")
   604     public native Class<? super T> getSuperclass();
   605 
   606     /**
   607      * Returns the Java language modifiers for this class or interface, encoded
   608      * in an integer. The modifiers consist of the Java Virtual Machine's
   609      * constants for {@code public}, {@code protected},
   610      * {@code private}, {@code final}, {@code static},
   611      * {@code abstract} and {@code interface}; they should be decoded
   612      * using the methods of class {@code Modifier}.
   613      *
   614      * <p> If the underlying class is an array class, then its
   615      * {@code public}, {@code private} and {@code protected}
   616      * modifiers are the same as those of its component type.  If this
   617      * {@code Class} represents a primitive type or void, its
   618      * {@code public} modifier is always {@code true}, and its
   619      * {@code protected} and {@code private} modifiers are always
   620      * {@code false}. If this object represents an array class, a
   621      * primitive type or void, then its {@code final} modifier is always
   622      * {@code true} and its interface modifier is always
   623      * {@code false}. The values of its other modifiers are not determined
   624      * by this specification.
   625      *
   626      * <p> The modifier encodings are defined in <em>The Java Virtual Machine
   627      * Specification</em>, table 4.1.
   628      *
   629      * @return the {@code int} representing the modifiers for this class
   630      * @see     java.lang.reflect.Modifier
   631      * @since JDK1.1
   632      */
   633     public int getModifiers() {
   634         return getAccess();
   635     }
   636 
   637     /**
   638      * If the class or interface represented by this {@code Class} object
   639      * is a member of another class, returns the {@code Class} object
   640      * representing the class in which it was declared.  This method returns
   641      * null if this class or interface is not a member of any other class.  If
   642      * this {@code Class} object represents an array class, a primitive
   643      * type, or void,then this method returns null.
   644      *
   645      * @return the declaring class for this class
   646      * @since JDK1.1
   647      */
   648     public Class<?> getDeclaringClass() {
   649         throw new SecurityException();
   650     }
   651 
   652     /**
   653      * Returns the simple name of the underlying class as given in the
   654      * source code. Returns an empty string if the underlying class is
   655      * anonymous.
   656      *
   657      * <p>The simple name of an array is the simple name of the
   658      * component type with "[]" appended.  In particular the simple
   659      * name of an array whose component type is anonymous is "[]".
   660      *
   661      * @return the simple name of the underlying class
   662      * @since 1.5
   663      */
   664     public String getSimpleName() {
   665         if (isArray())
   666             return getComponentType().getSimpleName()+"[]";
   667 
   668         String simpleName = getSimpleBinaryName();
   669         if (simpleName == null) { // top level class
   670             simpleName = getName();
   671             return simpleName.substring(simpleName.lastIndexOf(".")+1); // strip the package name
   672         }
   673         // According to JLS3 "Binary Compatibility" (13.1) the binary
   674         // name of non-package classes (not top level) is the binary
   675         // name of the immediately enclosing class followed by a '$' followed by:
   676         // (for nested and inner classes): the simple name.
   677         // (for local classes): 1 or more digits followed by the simple name.
   678         // (for anonymous classes): 1 or more digits.
   679 
   680         // Since getSimpleBinaryName() will strip the binary name of
   681         // the immediatly enclosing class, we are now looking at a
   682         // string that matches the regular expression "\$[0-9]*"
   683         // followed by a simple name (considering the simple of an
   684         // anonymous class to be the empty string).
   685 
   686         // Remove leading "\$[0-9]*" from the name
   687         int length = simpleName.length();
   688         if (length < 1 || simpleName.charAt(0) != '$')
   689             throw new IllegalStateException("Malformed class name");
   690         int index = 1;
   691         while (index < length && isAsciiDigit(simpleName.charAt(index)))
   692             index++;
   693         // Eventually, this is the empty string iff this is an anonymous class
   694         return simpleName.substring(index);
   695     }
   696 
   697     /**
   698      * Returns the "simple binary name" of the underlying class, i.e.,
   699      * the binary name without the leading enclosing class name.
   700      * Returns {@code null} if the underlying class is a top level
   701      * class.
   702      */
   703     private String getSimpleBinaryName() {
   704         Class<?> enclosingClass = null; // XXX getEnclosingClass();
   705         if (enclosingClass == null) // top level class
   706             return null;
   707         // Otherwise, strip the enclosing class' name
   708         try {
   709             return getName().substring(enclosingClass.getName().length());
   710         } catch (IndexOutOfBoundsException ex) {
   711             throw new IllegalStateException("Malformed class name");
   712         }
   713     }
   714 
   715     /**
   716      * Returns an array containing {@code Field} objects reflecting all
   717      * the accessible public fields of the class or interface represented by
   718      * this {@code Class} object.  The elements in the array returned are
   719      * not sorted and are not in any particular order.  This method returns an
   720      * array of length 0 if the class or interface has no accessible public
   721      * fields, or if it represents an array class, a primitive type, or void.
   722      *
   723      * <p> Specifically, if this {@code Class} object represents a class,
   724      * this method returns the public fields of this class and of all its
   725      * superclasses.  If this {@code Class} object represents an
   726      * interface, this method returns the fields of this interface and of all
   727      * its superinterfaces.
   728      *
   729      * <p> The implicit length field for array class is not reflected by this
   730      * method. User code should use the methods of class {@code Array} to
   731      * manipulate arrays.
   732      *
   733      * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3.
   734      *
   735      * @return the array of {@code Field} objects representing the
   736      * public fields
   737      * @exception  SecurityException
   738      *             If a security manager, <i>s</i>, is present and any of the
   739      *             following conditions is met:
   740      *
   741      *             <ul>
   742      *
   743      *             <li> invocation of
   744      *             {@link SecurityManager#checkMemberAccess
   745      *             s.checkMemberAccess(this, Member.PUBLIC)} denies
   746      *             access to the fields within this class
   747      *
   748      *             <li> the caller's class loader is not the same as or an
   749      *             ancestor of the class loader for the current class and
   750      *             invocation of {@link SecurityManager#checkPackageAccess
   751      *             s.checkPackageAccess()} denies access to the package
   752      *             of this class
   753      *
   754      *             </ul>
   755      *
   756      * @since JDK1.1
   757      */
   758     public Field[] getFields() throws SecurityException {
   759         throw new SecurityException();
   760     }
   761 
   762     /**
   763      * Returns an array containing {@code Method} objects reflecting all
   764      * the public <em>member</em> methods of the class or interface represented
   765      * by this {@code Class} object, including those declared by the class
   766      * or interface and those inherited from superclasses and
   767      * superinterfaces.  Array classes return all the (public) member methods
   768      * inherited from the {@code Object} class.  The elements in the array
   769      * returned are not sorted and are not in any particular order.  This
   770      * method returns an array of length 0 if this {@code Class} object
   771      * represents a class or interface that has no public member methods, or if
   772      * this {@code Class} object represents a primitive type or void.
   773      *
   774      * <p> The class initialization method {@code <clinit>} is not
   775      * included in the returned array. If the class declares multiple public
   776      * member methods with the same parameter types, they are all included in
   777      * the returned array.
   778      *
   779      * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.4.
   780      *
   781      * @return the array of {@code Method} objects representing the
   782      * public methods of this class
   783      * @exception  SecurityException
   784      *             If a security manager, <i>s</i>, is present and any of the
   785      *             following conditions is met:
   786      *
   787      *             <ul>
   788      *
   789      *             <li> invocation of
   790      *             {@link SecurityManager#checkMemberAccess
   791      *             s.checkMemberAccess(this, Member.PUBLIC)} denies
   792      *             access to the methods within this class
   793      *
   794      *             <li> the caller's class loader is not the same as or an
   795      *             ancestor of the class loader for the current class and
   796      *             invocation of {@link SecurityManager#checkPackageAccess
   797      *             s.checkPackageAccess()} denies access to the package
   798      *             of this class
   799      *
   800      *             </ul>
   801      *
   802      * @since JDK1.1
   803      */
   804     public Method[] getMethods() throws SecurityException {
   805         return MethodImpl.findMethods(this, 0x01);
   806     }
   807 
   808     /**
   809      * Returns a {@code Field} object that reflects the specified public
   810      * member field of the class or interface represented by this
   811      * {@code Class} object. The {@code name} parameter is a
   812      * {@code String} specifying the simple name of the desired field.
   813      *
   814      * <p> The field to be reflected is determined by the algorithm that
   815      * follows.  Let C be the class represented by this object:
   816      * <OL>
   817      * <LI> If C declares a public field with the name specified, that is the
   818      *      field to be reflected.</LI>
   819      * <LI> If no field was found in step 1 above, this algorithm is applied
   820      *      recursively to each direct superinterface of C. The direct
   821      *      superinterfaces are searched in the order they were declared.</LI>
   822      * <LI> If no field was found in steps 1 and 2 above, and C has a
   823      *      superclass S, then this algorithm is invoked recursively upon S.
   824      *      If C has no superclass, then a {@code NoSuchFieldException}
   825      *      is thrown.</LI>
   826      * </OL>
   827      *
   828      * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3.
   829      *
   830      * @param name the field name
   831      * @return  the {@code Field} object of this class specified by
   832      * {@code name}
   833      * @exception NoSuchFieldException if a field with the specified name is
   834      *              not found.
   835      * @exception NullPointerException if {@code name} is {@code null}
   836      * @exception  SecurityException
   837      *             If a security manager, <i>s</i>, is present and any of the
   838      *             following conditions is met:
   839      *
   840      *             <ul>
   841      *
   842      *             <li> invocation of
   843      *             {@link SecurityManager#checkMemberAccess
   844      *             s.checkMemberAccess(this, Member.PUBLIC)} denies
   845      *             access to the field
   846      *
   847      *             <li> the caller's class loader is not the same as or an
   848      *             ancestor of the class loader for the current class and
   849      *             invocation of {@link SecurityManager#checkPackageAccess
   850      *             s.checkPackageAccess()} denies access to the package
   851      *             of this class
   852      *
   853      *             </ul>
   854      *
   855      * @since JDK1.1
   856      */
   857     public Field getField(String name)
   858         throws SecurityException {
   859         throw new SecurityException();
   860     }
   861     
   862     
   863     /**
   864      * Returns a {@code Method} object that reflects the specified public
   865      * member method of the class or interface represented by this
   866      * {@code Class} object. The {@code name} parameter is a
   867      * {@code String} specifying the simple name of the desired method. The
   868      * {@code parameterTypes} parameter is an array of {@code Class}
   869      * objects that identify the method's formal parameter types, in declared
   870      * order. If {@code parameterTypes} is {@code null}, it is
   871      * treated as if it were an empty array.
   872      *
   873      * <p> If the {@code name} is "{@code <init>};"or "{@code <clinit>}" a
   874      * {@code NoSuchMethodException} is raised. Otherwise, the method to
   875      * be reflected is determined by the algorithm that follows.  Let C be the
   876      * class represented by this object:
   877      * <OL>
   878      * <LI> C is searched for any <I>matching methods</I>. If no matching
   879      *      method is found, the algorithm of step 1 is invoked recursively on
   880      *      the superclass of C.</LI>
   881      * <LI> If no method was found in step 1 above, the superinterfaces of C
   882      *      are searched for a matching method. If any such method is found, it
   883      *      is reflected.</LI>
   884      * </OL>
   885      *
   886      * To find a matching method in a class C:&nbsp; If C declares exactly one
   887      * public method with the specified name and exactly the same formal
   888      * parameter types, that is the method reflected. If more than one such
   889      * method is found in C, and one of these methods has a return type that is
   890      * more specific than any of the others, that method is reflected;
   891      * otherwise one of the methods is chosen arbitrarily.
   892      *
   893      * <p>Note that there may be more than one matching method in a
   894      * class because while the Java language forbids a class to
   895      * declare multiple methods with the same signature but different
   896      * return types, the Java virtual machine does not.  This
   897      * increased flexibility in the virtual machine can be used to
   898      * implement various language features.  For example, covariant
   899      * returns can be implemented with {@linkplain
   900      * java.lang.reflect.Method#isBridge bridge methods}; the bridge
   901      * method and the method being overridden would have the same
   902      * signature but different return types.
   903      *
   904      * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.4.
   905      *
   906      * @param name the name of the method
   907      * @param parameterTypes the list of parameters
   908      * @return the {@code Method} object that matches the specified
   909      * {@code name} and {@code parameterTypes}
   910      * @exception NoSuchMethodException if a matching method is not found
   911      *            or if the name is "&lt;init&gt;"or "&lt;clinit&gt;".
   912      * @exception NullPointerException if {@code name} is {@code null}
   913      * @exception  SecurityException
   914      *             If a security manager, <i>s</i>, is present and any of the
   915      *             following conditions is met:
   916      *
   917      *             <ul>
   918      *
   919      *             <li> invocation of
   920      *             {@link SecurityManager#checkMemberAccess
   921      *             s.checkMemberAccess(this, Member.PUBLIC)} denies
   922      *             access to the method
   923      *
   924      *             <li> the caller's class loader is not the same as or an
   925      *             ancestor of the class loader for the current class and
   926      *             invocation of {@link SecurityManager#checkPackageAccess
   927      *             s.checkPackageAccess()} denies access to the package
   928      *             of this class
   929      *
   930      *             </ul>
   931      *
   932      * @since JDK1.1
   933      */
   934     public Method getMethod(String name, Class<?>... parameterTypes)
   935         throws SecurityException, NoSuchMethodException {
   936         Method m = MethodImpl.findMethod(this, name, parameterTypes);
   937         if (m == null) {
   938             StringBuilder sb = new StringBuilder();
   939             sb.append(getName()).append('.').append(name).append('(');
   940             String sep = "";
   941             for (int i = 0; i < parameterTypes.length; i++) {
   942                 sb.append(sep).append(parameterTypes[i].getName());
   943                 sep = ", ";
   944             }
   945             sb.append(')');
   946             throw new NoSuchMethodException(sb.toString());
   947         }
   948         return m;
   949     }
   950     
   951     /**
   952      * Returns an array of {@code Method} objects reflecting all the
   953      * methods declared by the class or interface represented by this
   954      * {@code Class} object. This includes public, protected, default
   955      * (package) access, and private methods, but excludes inherited methods.
   956      * The elements in the array returned are not sorted and are not in any
   957      * particular order.  This method returns an array of length 0 if the class
   958      * or interface declares no methods, or if this {@code Class} object
   959      * represents a primitive type, an array class, or void.  The class
   960      * initialization method {@code <clinit>} is not included in the
   961      * returned array. If the class declares multiple public member methods
   962      * with the same parameter types, they are all included in the returned
   963      * array.
   964      *
   965      * <p> See <em>The Java Language Specification</em>, section 8.2.
   966      *
   967      * @return    the array of {@code Method} objects representing all the
   968      * declared methods of this class
   969      * @exception  SecurityException
   970      *             If a security manager, <i>s</i>, is present and any of the
   971      *             following conditions is met:
   972      *
   973      *             <ul>
   974      *
   975      *             <li> invocation of
   976      *             {@link SecurityManager#checkMemberAccess
   977      *             s.checkMemberAccess(this, Member.DECLARED)} denies
   978      *             access to the declared methods within this class
   979      *
   980      *             <li> the caller's class loader is not the same as or an
   981      *             ancestor of the class loader for the current class and
   982      *             invocation of {@link SecurityManager#checkPackageAccess
   983      *             s.checkPackageAccess()} denies access to the package
   984      *             of this class
   985      *
   986      *             </ul>
   987      *
   988      * @since JDK1.1
   989      */
   990     public Method[] getDeclaredMethods() throws SecurityException {
   991         throw new SecurityException();
   992     }
   993     
   994     /**
   995      * Returns an array of {@code Field} objects reflecting all the fields
   996      * declared by the class or interface represented by this
   997      * {@code Class} object. This includes public, protected, default
   998      * (package) access, and private fields, but excludes inherited fields.
   999      * The elements in the array returned are not sorted and are not in any
  1000      * particular order.  This method returns an array of length 0 if the class
  1001      * or interface declares no fields, or if this {@code Class} object
  1002      * represents a primitive type, an array class, or void.
  1003      *
  1004      * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3.
  1005      *
  1006      * @return    the array of {@code Field} objects representing all the
  1007      * declared fields of this class
  1008      * @exception  SecurityException
  1009      *             If a security manager, <i>s</i>, is present and any of the
  1010      *             following conditions is met:
  1011      *
  1012      *             <ul>
  1013      *
  1014      *             <li> invocation of
  1015      *             {@link SecurityManager#checkMemberAccess
  1016      *             s.checkMemberAccess(this, Member.DECLARED)} denies
  1017      *             access to the declared fields within this class
  1018      *
  1019      *             <li> the caller's class loader is not the same as or an
  1020      *             ancestor of the class loader for the current class and
  1021      *             invocation of {@link SecurityManager#checkPackageAccess
  1022      *             s.checkPackageAccess()} denies access to the package
  1023      *             of this class
  1024      *
  1025      *             </ul>
  1026      *
  1027      * @since JDK1.1
  1028      */
  1029     public Field[] getDeclaredFields() throws SecurityException {
  1030         throw new SecurityException();
  1031     }
  1032 
  1033     /**
  1034      * <b>Bck2Brwsr</b> emulation can only seek public methods, otherwise it
  1035      * throws a {@code SecurityException}.
  1036      * <p>
  1037      * Returns a {@code Method} object that reflects the specified
  1038      * declared method of the class or interface represented by this
  1039      * {@code Class} object. The {@code name} parameter is a
  1040      * {@code String} that specifies the simple name of the desired
  1041      * method, and the {@code parameterTypes} parameter is an array of
  1042      * {@code Class} objects that identify the method's formal parameter
  1043      * types, in declared order.  If more than one method with the same
  1044      * parameter types is declared in a class, and one of these methods has a
  1045      * return type that is more specific than any of the others, that method is
  1046      * returned; otherwise one of the methods is chosen arbitrarily.  If the
  1047      * name is "&lt;init&gt;"or "&lt;clinit&gt;" a {@code NoSuchMethodException}
  1048      * is raised.
  1049      *
  1050      * @param name the name of the method
  1051      * @param parameterTypes the parameter array
  1052      * @return    the {@code Method} object for the method of this class
  1053      * matching the specified name and parameters
  1054      * @exception NoSuchMethodException if a matching method is not found.
  1055      * @exception NullPointerException if {@code name} is {@code null}
  1056      * @exception  SecurityException
  1057      *             If a security manager, <i>s</i>, is present and any of the
  1058      *             following conditions is met:
  1059      *
  1060      *             <ul>
  1061      *
  1062      *             <li> invocation of
  1063      *             {@link SecurityManager#checkMemberAccess
  1064      *             s.checkMemberAccess(this, Member.DECLARED)} denies
  1065      *             access to the declared method
  1066      *
  1067      *             <li> the caller's class loader is not the same as or an
  1068      *             ancestor of the class loader for the current class and
  1069      *             invocation of {@link SecurityManager#checkPackageAccess
  1070      *             s.checkPackageAccess()} denies access to the package
  1071      *             of this class
  1072      *
  1073      *             </ul>
  1074      *
  1075      * @since JDK1.1
  1076      */
  1077     public Method getDeclaredMethod(String name, Class<?>... parameterTypes)
  1078     throws NoSuchMethodException, SecurityException {
  1079         try {
  1080             return getMethod(name, parameterTypes);
  1081         } catch (NoSuchMethodException ex) {
  1082             throw new SecurityException();
  1083         }
  1084     }
  1085 
  1086     /**
  1087      * Returns a {@code Field} object that reflects the specified declared
  1088      * field of the class or interface represented by this {@code Class}
  1089      * object. The {@code name} parameter is a {@code String} that
  1090      * specifies the simple name of the desired field.  Note that this method
  1091      * will not reflect the {@code length} field of an array class.
  1092      *
  1093      * @param name the name of the field
  1094      * @return the {@code Field} object for the specified field in this
  1095      * class
  1096      * @exception NoSuchFieldException if a field with the specified name is
  1097      *              not found.
  1098      * @exception NullPointerException if {@code name} is {@code null}
  1099      * @exception  SecurityException
  1100      *             If a security manager, <i>s</i>, is present and any of the
  1101      *             following conditions is met:
  1102      *
  1103      *             <ul>
  1104      *
  1105      *             <li> invocation of
  1106      *             {@link SecurityManager#checkMemberAccess
  1107      *             s.checkMemberAccess(this, Member.DECLARED)} denies
  1108      *             access to the declared field
  1109      *
  1110      *             <li> the caller's class loader is not the same as or an
  1111      *             ancestor of the class loader for the current class and
  1112      *             invocation of {@link SecurityManager#checkPackageAccess
  1113      *             s.checkPackageAccess()} denies access to the package
  1114      *             of this class
  1115      *
  1116      *             </ul>
  1117      *
  1118      * @since JDK1.1
  1119      */
  1120     public Field getDeclaredField(String name)
  1121     throws SecurityException {
  1122         throw new SecurityException();
  1123     }
  1124     
  1125     /**
  1126      * Returns an array containing {@code Constructor} objects reflecting
  1127      * all the public constructors of the class represented by this
  1128      * {@code Class} object.  An array of length 0 is returned if the
  1129      * class has no public constructors, or if the class is an array class, or
  1130      * if the class reflects a primitive type or void.
  1131      *
  1132      * Note that while this method returns an array of {@code
  1133      * Constructor<T>} objects (that is an array of constructors from
  1134      * this class), the return type of this method is {@code
  1135      * Constructor<?>[]} and <em>not</em> {@code Constructor<T>[]} as
  1136      * might be expected.  This less informative return type is
  1137      * necessary since after being returned from this method, the
  1138      * array could be modified to hold {@code Constructor} objects for
  1139      * different classes, which would violate the type guarantees of
  1140      * {@code Constructor<T>[]}.
  1141      *
  1142      * @return the array of {@code Constructor} objects representing the
  1143      *  public constructors of this class
  1144      * @exception  SecurityException
  1145      *             If a security manager, <i>s</i>, is present and any of the
  1146      *             following conditions is met:
  1147      *
  1148      *             <ul>
  1149      *
  1150      *             <li> invocation of
  1151      *             {@link SecurityManager#checkMemberAccess
  1152      *             s.checkMemberAccess(this, Member.PUBLIC)} denies
  1153      *             access to the constructors within this class
  1154      *
  1155      *             <li> the caller's class loader is not the same as or an
  1156      *             ancestor of the class loader for the current class and
  1157      *             invocation of {@link SecurityManager#checkPackageAccess
  1158      *             s.checkPackageAccess()} denies access to the package
  1159      *             of this class
  1160      *
  1161      *             </ul>
  1162      *
  1163      * @since JDK1.1
  1164      */
  1165     public Constructor<?>[] getConstructors() throws SecurityException {
  1166         return MethodImpl.findConstructors(this, 0x01);
  1167     }
  1168 
  1169     /**
  1170      * Returns a {@code Constructor} object that reflects the specified
  1171      * public constructor of the class represented by this {@code Class}
  1172      * object. The {@code parameterTypes} parameter is an array of
  1173      * {@code Class} objects that identify the constructor's formal
  1174      * parameter types, in declared order.
  1175      *
  1176      * If this {@code Class} object represents an inner class
  1177      * declared in a non-static context, the formal parameter types
  1178      * include the explicit enclosing instance as the first parameter.
  1179      *
  1180      * <p> The constructor to reflect is the public constructor of the class
  1181      * represented by this {@code Class} object whose formal parameter
  1182      * types match those specified by {@code parameterTypes}.
  1183      *
  1184      * @param parameterTypes the parameter array
  1185      * @return the {@code Constructor} object of the public constructor that
  1186      * matches the specified {@code parameterTypes}
  1187      * @exception NoSuchMethodException if a matching method is not found.
  1188      * @exception  SecurityException
  1189      *             If a security manager, <i>s</i>, is present and any of the
  1190      *             following conditions is met:
  1191      *
  1192      *             <ul>
  1193      *
  1194      *             <li> invocation of
  1195      *             {@link SecurityManager#checkMemberAccess
  1196      *             s.checkMemberAccess(this, Member.PUBLIC)} denies
  1197      *             access to the constructor
  1198      *
  1199      *             <li> the caller's class loader is not the same as or an
  1200      *             ancestor of the class loader for the current class and
  1201      *             invocation of {@link SecurityManager#checkPackageAccess
  1202      *             s.checkPackageAccess()} denies access to the package
  1203      *             of this class
  1204      *
  1205      *             </ul>
  1206      *
  1207      * @since JDK1.1
  1208      */
  1209     public Constructor<T> getConstructor(Class<?>... parameterTypes)
  1210     throws NoSuchMethodException, SecurityException {
  1211         Constructor c = MethodImpl.findConstructor(this, parameterTypes);
  1212         if (c == null) {
  1213             StringBuilder sb = new StringBuilder();
  1214             sb.append(getName()).append('(');
  1215             String sep = "";
  1216             for (int i = 0; i < parameterTypes.length; i++) {
  1217                 sb.append(sep).append(parameterTypes[i].getName());
  1218                 sep = ", ";
  1219             }
  1220             sb.append(')');
  1221             throw new NoSuchMethodException(sb.toString());
  1222         }
  1223         return c;
  1224     }
  1225 
  1226     /**
  1227      * Returns an array of {@code Constructor} objects reflecting all the
  1228      * constructors declared by the class represented by this
  1229      * {@code Class} object. These are public, protected, default
  1230      * (package) access, and private constructors.  The elements in the array
  1231      * returned are not sorted and are not in any particular order.  If the
  1232      * class has a default constructor, it is included in the returned array.
  1233      * This method returns an array of length 0 if this {@code Class}
  1234      * object represents an interface, a primitive type, an array class, or
  1235      * void.
  1236      *
  1237      * <p> See <em>The Java Language Specification</em>, section 8.2.
  1238      *
  1239      * @return    the array of {@code Constructor} objects representing all the
  1240      * declared constructors of this class
  1241      * @exception  SecurityException
  1242      *             If a security manager, <i>s</i>, is present and any of the
  1243      *             following conditions is met:
  1244      *
  1245      *             <ul>
  1246      *
  1247      *             <li> invocation of
  1248      *             {@link SecurityManager#checkMemberAccess
  1249      *             s.checkMemberAccess(this, Member.DECLARED)} denies
  1250      *             access to the declared constructors within this class
  1251      *
  1252      *             <li> the caller's class loader is not the same as or an
  1253      *             ancestor of the class loader for the current class and
  1254      *             invocation of {@link SecurityManager#checkPackageAccess
  1255      *             s.checkPackageAccess()} denies access to the package
  1256      *             of this class
  1257      *
  1258      *             </ul>
  1259      *
  1260      * @since JDK1.1
  1261      */
  1262     public Constructor<?>[] getDeclaredConstructors() throws SecurityException {
  1263         throw new SecurityException();
  1264     }
  1265     /**
  1266      * Returns a {@code Constructor} object that reflects the specified
  1267      * constructor of the class or interface represented by this
  1268      * {@code Class} object.  The {@code parameterTypes} parameter is
  1269      * an array of {@code Class} objects that identify the constructor's
  1270      * formal parameter types, in declared order.
  1271      *
  1272      * If this {@code Class} object represents an inner class
  1273      * declared in a non-static context, the formal parameter types
  1274      * include the explicit enclosing instance as the first parameter.
  1275      *
  1276      * @param parameterTypes the parameter array
  1277      * @return    The {@code Constructor} object for the constructor with the
  1278      * specified parameter list
  1279      * @exception NoSuchMethodException if a matching method is not found.
  1280      * @exception  SecurityException
  1281      *             If a security manager, <i>s</i>, is present and any of the
  1282      *             following conditions is met:
  1283      *
  1284      *             <ul>
  1285      *
  1286      *             <li> invocation of
  1287      *             {@link SecurityManager#checkMemberAccess
  1288      *             s.checkMemberAccess(this, Member.DECLARED)} denies
  1289      *             access to the declared constructor
  1290      *
  1291      *             <li> the caller's class loader is not the same as or an
  1292      *             ancestor of the class loader for the current class and
  1293      *             invocation of {@link SecurityManager#checkPackageAccess
  1294      *             s.checkPackageAccess()} denies access to the package
  1295      *             of this class
  1296      *
  1297      *             </ul>
  1298      *
  1299      * @since JDK1.1
  1300      */
  1301     public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)
  1302     throws NoSuchMethodException, SecurityException {
  1303         return getConstructor(parameterTypes);
  1304     }
  1305     
  1306     
  1307     /**
  1308      * Character.isDigit answers {@code true} to some non-ascii
  1309      * digits.  This one does not.
  1310      */
  1311     private static boolean isAsciiDigit(char c) {
  1312         return '0' <= c && c <= '9';
  1313     }
  1314 
  1315     /**
  1316      * Returns the canonical name of the underlying class as
  1317      * defined by the Java Language Specification.  Returns null if
  1318      * the underlying class does not have a canonical name (i.e., if
  1319      * it is a local or anonymous class or an array whose component
  1320      * type does not have a canonical name).
  1321      * @return the canonical name of the underlying class if it exists, and
  1322      * {@code null} otherwise.
  1323      * @since 1.5
  1324      */
  1325     public String getCanonicalName() {
  1326         if (isArray()) {
  1327             String canonicalName = getComponentType().getCanonicalName();
  1328             if (canonicalName != null)
  1329                 return canonicalName + "[]";
  1330             else
  1331                 return null;
  1332         }
  1333 //        if (isLocalOrAnonymousClass())
  1334 //            return null;
  1335 //        Class<?> enclosingClass = getEnclosingClass();
  1336         Class<?> enclosingClass = null;
  1337         if (enclosingClass == null) { // top level class
  1338             return getName();
  1339         } else {
  1340             String enclosingName = enclosingClass.getCanonicalName();
  1341             if (enclosingName == null)
  1342                 return null;
  1343             return enclosingName + "." + getSimpleName();
  1344         }
  1345     }
  1346 
  1347     /**
  1348      * Finds a resource with a given name.  The rules for searching resources
  1349      * associated with a given class are implemented by the defining
  1350      * {@linkplain ClassLoader class loader} of the class.  This method
  1351      * delegates to this object's class loader.  If this object was loaded by
  1352      * the bootstrap class loader, the method delegates to {@link
  1353      * ClassLoader#getSystemResourceAsStream}.
  1354      *
  1355      * <p> Before delegation, an absolute resource name is constructed from the
  1356      * given resource name using this algorithm:
  1357      *
  1358      * <ul>
  1359      *
  1360      * <li> If the {@code name} begins with a {@code '/'}
  1361      * (<tt>'&#92;u002f'</tt>), then the absolute name of the resource is the
  1362      * portion of the {@code name} following the {@code '/'}.
  1363      *
  1364      * <li> Otherwise, the absolute name is of the following form:
  1365      *
  1366      * <blockquote>
  1367      *   {@code modified_package_name/name}
  1368      * </blockquote>
  1369      *
  1370      * <p> Where the {@code modified_package_name} is the package name of this
  1371      * object with {@code '/'} substituted for {@code '.'}
  1372      * (<tt>'&#92;u002e'</tt>).
  1373      *
  1374      * </ul>
  1375      *
  1376      * @param  name name of the desired resource
  1377      * @return      A {@link java.io.InputStream} object or {@code null} if
  1378      *              no resource with this name is found
  1379      * @throws  NullPointerException If {@code name} is {@code null}
  1380      * @since  JDK1.1
  1381      */
  1382      public InputStream getResourceAsStream(String name) {
  1383         name = resolveName(name);
  1384         byte[] arr = ClassLoader.getResourceAsStream0(name, 0);
  1385         return arr == null ? null : new ByteArrayInputStream(arr);
  1386      }
  1387     
  1388     /**
  1389      * Finds a resource with a given name.  The rules for searching resources
  1390      * associated with a given class are implemented by the defining
  1391      * {@linkplain ClassLoader class loader} of the class.  This method
  1392      * delegates to this object's class loader.  If this object was loaded by
  1393      * the bootstrap class loader, the method delegates to {@link
  1394      * ClassLoader#getSystemResource}.
  1395      *
  1396      * <p> Before delegation, an absolute resource name is constructed from the
  1397      * given resource name using this algorithm:
  1398      *
  1399      * <ul>
  1400      *
  1401      * <li> If the {@code name} begins with a {@code '/'}
  1402      * (<tt>'&#92;u002f'</tt>), then the absolute name of the resource is the
  1403      * portion of the {@code name} following the {@code '/'}.
  1404      *
  1405      * <li> Otherwise, the absolute name is of the following form:
  1406      *
  1407      * <blockquote>
  1408      *   {@code modified_package_name/name}
  1409      * </blockquote>
  1410      *
  1411      * <p> Where the {@code modified_package_name} is the package name of this
  1412      * object with {@code '/'} substituted for {@code '.'}
  1413      * (<tt>'&#92;u002e'</tt>).
  1414      *
  1415      * </ul>
  1416      *
  1417      * @param  name name of the desired resource
  1418      * @return      A  {@link java.net.URL} object or {@code null} if no
  1419      *              resource with this name is found
  1420      * @since  JDK1.1
  1421      */
  1422     public java.net.URL getResource(String name) {
  1423         return newResourceURL(name, getResourceAsStream(name));
  1424     }
  1425 
  1426     static URL newResourceURL(String name, InputStream is) {
  1427         return is == null ? null : newResourceURL0(URL.class, "res:/" + name, is);
  1428     }
  1429     
  1430     @JavaScriptBody(args = { "url", "spec", "is" }, body = 
  1431         "var u = url.cnstr(true);\n"
  1432       + "u.constructor.cons__VLjava_lang_String_2Ljava_io_InputStream_2.call(u, spec, is);\n"
  1433       + "return u;"
  1434     )
  1435     private static native URL newResourceURL0(Class<URL> url, String spec, InputStream is);
  1436 
  1437    /**
  1438      * Add a package name prefix if the name is not absolute Remove leading "/"
  1439      * if name is absolute
  1440      */
  1441     private String resolveName(String name) {
  1442         if (name == null) {
  1443             return name;
  1444         }
  1445         if (!name.startsWith("/")) {
  1446             Class<?> c = this;
  1447             while (c.isArray()) {
  1448                 c = c.getComponentType();
  1449             }
  1450             String baseName = c.getName();
  1451             int index = baseName.lastIndexOf('.');
  1452             if (index != -1) {
  1453                 name = baseName.substring(0, index).replace('.', '/')
  1454                     +"/"+name;
  1455             }
  1456         } else {
  1457             name = name.substring(1);
  1458         }
  1459         return name;
  1460     }
  1461     
  1462     /**
  1463      * Returns the class loader for the class.  Some implementations may use
  1464      * null to represent the bootstrap class loader. This method will return
  1465      * null in such implementations if this class was loaded by the bootstrap
  1466      * class loader.
  1467      *
  1468      * <p> If a security manager is present, and the caller's class loader is
  1469      * not null and the caller's class loader is not the same as or an ancestor of
  1470      * the class loader for the class whose class loader is requested, then
  1471      * this method calls the security manager's {@code checkPermission}
  1472      * method with a {@code RuntimePermission("getClassLoader")}
  1473      * permission to ensure it's ok to access the class loader for the class.
  1474      *
  1475      * <p>If this object
  1476      * represents a primitive type or void, null is returned.
  1477      *
  1478      * @return  the class loader that loaded the class or interface
  1479      *          represented by this object.
  1480      * @throws SecurityException
  1481      *    if a security manager exists and its
  1482      *    {@code checkPermission} method denies
  1483      *    access to the class loader for the class.
  1484      * @see java.lang.ClassLoader
  1485      * @see SecurityManager#checkPermission
  1486      * @see java.lang.RuntimePermission
  1487      */
  1488     public ClassLoader getClassLoader() {
  1489         return ClassLoader.getSystemClassLoader();
  1490     }
  1491 
  1492     /**
  1493      * Determines the interfaces implemented by the class or interface
  1494      * represented by this object.
  1495      *
  1496      * <p> If this object represents a class, the return value is an array
  1497      * containing objects representing all interfaces implemented by the
  1498      * class. The order of the interface objects in the array corresponds to
  1499      * the order of the interface names in the {@code implements} clause
  1500      * of the declaration of the class represented by this object. For
  1501      * example, given the declaration:
  1502      * <blockquote>
  1503      * {@code class Shimmer implements FloorWax, DessertTopping { ... }}
  1504      * </blockquote>
  1505      * suppose the value of {@code s} is an instance of
  1506      * {@code Shimmer}; the value of the expression:
  1507      * <blockquote>
  1508      * {@code s.getClass().getInterfaces()[0]}
  1509      * </blockquote>
  1510      * is the {@code Class} object that represents interface
  1511      * {@code FloorWax}; and the value of:
  1512      * <blockquote>
  1513      * {@code s.getClass().getInterfaces()[1]}
  1514      * </blockquote>
  1515      * is the {@code Class} object that represents interface
  1516      * {@code DessertTopping}.
  1517      *
  1518      * <p> If this object represents an interface, the array contains objects
  1519      * representing all interfaces extended by the interface. The order of the
  1520      * interface objects in the array corresponds to the order of the interface
  1521      * names in the {@code extends} clause of the declaration of the
  1522      * interface represented by this object.
  1523      *
  1524      * <p> If this object represents a class or interface that implements no
  1525      * interfaces, the method returns an array of length 0.
  1526      *
  1527      * <p> If this object represents a primitive type or void, the method
  1528      * returns an array of length 0.
  1529      *
  1530      * @return an array of interfaces implemented by this class.
  1531      */
  1532     public native Class<?>[] getInterfaces();
  1533     
  1534     /**
  1535      * Returns the {@code Class} representing the component type of an
  1536      * array.  If this class does not represent an array class this method
  1537      * returns null.
  1538      *
  1539      * @return the {@code Class} representing the component type of this
  1540      * class if this class is an array
  1541      * @see     java.lang.reflect.Array
  1542      * @since JDK1.1
  1543      */
  1544     public Class<?> getComponentType() {
  1545         if (isArray()) {
  1546             try {
  1547                 return getComponentType0();
  1548             } catch (ClassNotFoundException cnfe) {
  1549                 throw new IllegalStateException(cnfe);
  1550             }
  1551         }
  1552         return null;
  1553     }
  1554 
  1555     private Class<?> getComponentType0() throws ClassNotFoundException {
  1556         String n = getName().substring(1);
  1557         switch (n.charAt(0)) {
  1558             case 'L': 
  1559                 n = n.substring(1, n.length() - 1);
  1560                 return Class.forName(n);
  1561             case 'I':
  1562                 return Integer.TYPE;
  1563             case 'J':
  1564                 return Long.TYPE;
  1565             case 'D':
  1566                 return Double.TYPE;
  1567             case 'F':
  1568                 return Float.TYPE;
  1569             case 'B':
  1570                 return Byte.TYPE;
  1571             case 'Z':
  1572                 return Boolean.TYPE;
  1573             case 'S':
  1574                 return Short.TYPE;
  1575             case 'V':
  1576                 return Void.TYPE;
  1577             case 'C':
  1578                 return Character.TYPE;
  1579             case '[':
  1580                 return defineArray(n);
  1581             default:
  1582                 throw new ClassNotFoundException("Unknown component type of " + getName());
  1583         }
  1584     }
  1585     
  1586     @JavaScriptBody(args = { "sig" }, body = 
  1587         "if (!sig) sig = '[Ljava/lang/Object;';\n" +
  1588         "var c = Array[sig];\n" +
  1589         "if (c) return c;\n" +
  1590         "c = vm.java_lang_Class(true);\n" +
  1591         "c.jvmName = sig;\n" +
  1592         "c.superclass = vm.java_lang_Object(false).$class;\n" +
  1593         "c.array = true;\n" +
  1594         "Array[sig] = c;\n" +
  1595         "return c;"
  1596     )
  1597     private static native Class<?> defineArray(String sig);
  1598     
  1599     /**
  1600      * Returns true if and only if this class was declared as an enum in the
  1601      * source code.
  1602      *
  1603      * @return true if and only if this class was declared as an enum in the
  1604      *     source code
  1605      * @since 1.5
  1606      */
  1607     public boolean isEnum() {
  1608         // An enum must both directly extend java.lang.Enum and have
  1609         // the ENUM bit set; classes for specialized enum constants
  1610         // don't do the former.
  1611         return (this.getModifiers() & ENUM) != 0 &&
  1612         this.getSuperclass() == java.lang.Enum.class;
  1613     }
  1614 
  1615     /**
  1616      * Casts an object to the class or interface represented
  1617      * by this {@code Class} object.
  1618      *
  1619      * @param obj the object to be cast
  1620      * @return the object after casting, or null if obj is null
  1621      *
  1622      * @throws ClassCastException if the object is not
  1623      * null and is not assignable to the type T.
  1624      *
  1625      * @since 1.5
  1626      */
  1627     public T cast(Object obj) {
  1628         if (obj != null && !isInstance(obj))
  1629             throw new ClassCastException(cannotCastMsg(obj));
  1630         return (T) obj;
  1631     }
  1632 
  1633     private String cannotCastMsg(Object obj) {
  1634         return "Cannot cast " + obj.getClass().getName() + " to " + getName();
  1635     }
  1636 
  1637     /**
  1638      * Casts this {@code Class} object to represent a subclass of the class
  1639      * represented by the specified class object.  Checks that that the cast
  1640      * is valid, and throws a {@code ClassCastException} if it is not.  If
  1641      * this method succeeds, it always returns a reference to this class object.
  1642      *
  1643      * <p>This method is useful when a client needs to "narrow" the type of
  1644      * a {@code Class} object to pass it to an API that restricts the
  1645      * {@code Class} objects that it is willing to accept.  A cast would
  1646      * generate a compile-time warning, as the correctness of the cast
  1647      * could not be checked at runtime (because generic types are implemented
  1648      * by erasure).
  1649      *
  1650      * @return this {@code Class} object, cast to represent a subclass of
  1651      *    the specified class object.
  1652      * @throws ClassCastException if this {@code Class} object does not
  1653      *    represent a subclass of the specified class (here "subclass" includes
  1654      *    the class itself).
  1655      * @since 1.5
  1656      */
  1657     public <U> Class<? extends U> asSubclass(Class<U> clazz) {
  1658         if (clazz.isAssignableFrom(this))
  1659             return (Class<? extends U>) this;
  1660         else
  1661             throw new ClassCastException(this.toString());
  1662     }
  1663 
  1664     @JavaScriptBody(args = { "ac" }, 
  1665         body = 
  1666           "if (this.anno) {\n"
  1667         + "  var r = this.anno['L' + ac.jvmName + ';'];\n"
  1668         + "  if (typeof r === 'undefined') r = null;\n"
  1669         + "  return r;\n"
  1670         + "} else return null;\n"
  1671     )
  1672     private Object getAnnotationData(Class<?> annotationClass) {
  1673         throw new UnsupportedOperationException();
  1674     }
  1675     /**
  1676      * @throws NullPointerException {@inheritDoc}
  1677      * @since 1.5
  1678      */
  1679     public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {
  1680         Object data = getAnnotationData(annotationClass);
  1681         return data == null ? null : AnnotationImpl.create(annotationClass, data);
  1682     }
  1683 
  1684     /**
  1685      * @throws NullPointerException {@inheritDoc}
  1686      * @since 1.5
  1687      */
  1688     @JavaScriptBody(args = { "ac" }, 
  1689         body = "if (this.anno && this.anno['L' + ac.jvmName + ';']) { return true; }"
  1690         + "else return false;"
  1691     )
  1692     public boolean isAnnotationPresent(
  1693         Class<? extends Annotation> annotationClass) {
  1694         if (annotationClass == null)
  1695             throw new NullPointerException();
  1696 
  1697         return getAnnotation(annotationClass) != null;
  1698     }
  1699 
  1700     @JavaScriptBody(args = {}, body = "return this.anno;")
  1701     private Object getAnnotationData() {
  1702         throw new UnsupportedOperationException();
  1703     }
  1704 
  1705     /**
  1706      * @since 1.5
  1707      */
  1708     public Annotation[] getAnnotations() {
  1709         Object data = getAnnotationData();
  1710         return data == null ? new Annotation[0] : AnnotationImpl.create(data);
  1711     }
  1712 
  1713     /**
  1714      * @since 1.5
  1715      */
  1716     public Annotation[] getDeclaredAnnotations()  {
  1717         throw new UnsupportedOperationException();
  1718     }
  1719 
  1720     @JavaScriptBody(args = "type", body = ""
  1721         + "var c = vm.java_lang_Class(true);"
  1722         + "c.jvmName = type;"
  1723         + "c.primitive = true;"
  1724         + "return c;"
  1725     )
  1726     native static Class getPrimitiveClass(String type);
  1727 
  1728     @JavaScriptBody(args = {}, body = 
  1729         "return vm.desiredAssertionStatus ? vm.desiredAssertionStatus : false;"
  1730     )
  1731     public native boolean desiredAssertionStatus();
  1732     
  1733     static void registerNatives() {
  1734         boolean assertsOn = false;
  1735         //       assert assertsOn = true;
  1736         if (assertsOn) {
  1737             try {
  1738                 Array.get(null, 0);
  1739             } catch (Throwable ex) {
  1740                 // ignore
  1741             }
  1742         }
  1743     }
  1744 
  1745     @JavaScriptBody(args = {}, body = "var p = vm.java_lang_Object(false);"
  1746             + "p.toString = function() { return this.toString__Ljava_lang_String_2(); };"
  1747     )
  1748     static native void registerToString();
  1749     
  1750     @JavaScriptBody(args = {"self"}, body
  1751             = "var c = self.constructor.$class;\n"
  1752             + "return c ? c : null;\n"
  1753     )
  1754     static native Class<?> classFor(Object self);
  1755     
  1756     @JavaScriptBody(args = { "self" }, body
  1757             = "if (self.$hashCode) return self.$hashCode;\n"
  1758             + "var h = self.computeHashCode__I ? self.computeHashCode__I() : Math.random() * Math.pow(2, 31);\n"
  1759             + "return self.$hashCode = h & h;"
  1760     )
  1761     static native int defaultHashCode(Object self);
  1762 
  1763     @JavaScriptBody(args = "self", body
  1764             = "\nif (!self['$instOf_java_lang_Cloneable']) {"
  1765             + "\n  return null;"
  1766             + "\n} else {"
  1767             + "\n  var clone = self.constructor(true);"
  1768             + "\n  var props = Object.getOwnPropertyNames(self);"
  1769             + "\n  for (var i = 0; i < props.length; i++) {"
  1770             + "\n    var p = props[i];"
  1771             + "\n    clone[p] = self[p];"
  1772             + "\n  };"
  1773             + "\n  return clone;"
  1774             + "\n}"
  1775     )
  1776     static native Object clone(Object self) throws CloneNotSupportedException;
  1777 
  1778     @JavaScriptOnly(name = "toJS", value = "function(v) {\n"
  1779         + "  if (v === null) return null;\n"
  1780         + "  if (Object.prototype.toString.call(v) === '[object Array]') {\n"
  1781         + "    return vm.org_apidesign_bck2brwsr_emul_lang_System(false).convArray__Ljava_lang_Object_2Ljava_lang_Object_2(v);\n"
  1782         + "  }\n"
  1783         + "  return v.valueOf();\n"
  1784         + "}\n"
  1785     )
  1786     static native int toJS();
  1787 
  1788     @JavaScriptOnly(name = "activate__Ljava_io_Closeable_2Lorg_apidesign_html_boot_spi_Fn$Presenter_2", value = "function() {\n"
  1789         + "  return vm.org_apidesign_bck2brwsr_emul_lang_System(false).activate__Ljava_io_Closeable_2();"
  1790         + "}\n"
  1791     )
  1792     static native int activate();
  1793     
  1794     private static Object bck2BrwsrCnvrt(Object o) {
  1795         if (o instanceof Throwable) {
  1796             return o;
  1797         }
  1798         final String msg = msg(o);
  1799         if (msg == null || msg.startsWith("TypeError")) {
  1800             return new NullPointerException(msg);
  1801         }
  1802         return new Throwable(msg);
  1803     }
  1804 
  1805     @JavaScriptBody(args = {"o"}, body = "return o ? o.toString() : null;")
  1806     private static native String msg(Object o);
  1807 
  1808     @JavaScriptOnly(name = "bck2BrwsrThrwrbl", value = "c.bck2BrwsrCnvrt__Ljava_lang_Object_2Ljava_lang_Object_2")
  1809     private static void bck2BrwsrCnvrtVM() {
  1810     }
  1811     
  1812 }