emul/src/main/java/java/lang/Class.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Tue, 04 Dec 2012 14:31:11 +0100
branchreflection
changeset 260 1d03cb35fbda
parent 251 0b33848114b1
child 261 5d1e20215d12
permissions -rw-r--r--
Removing default implementation from reflection APIs
     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.InputStream;
    29 import java.lang.annotation.Annotation;
    30 import java.lang.reflect.TypeVariable;
    31 import org.apidesign.bck2brwsr.core.JavaScriptBody;
    32 
    33 /**
    34  * Instances of the class {@code Class} represent classes and
    35  * interfaces in a running Java application.  An enum is a kind of
    36  * class and an annotation is a kind of interface.  Every array also
    37  * belongs to a class that is reflected as a {@code Class} object
    38  * that is shared by all arrays with the same element type and number
    39  * of dimensions.  The primitive Java types ({@code boolean},
    40  * {@code byte}, {@code char}, {@code short},
    41  * {@code int}, {@code long}, {@code float}, and
    42  * {@code double}), and the keyword {@code void} are also
    43  * represented as {@code Class} objects.
    44  *
    45  * <p> {@code Class} has no public constructor. Instead {@code Class}
    46  * objects are constructed automatically by the Java Virtual Machine as classes
    47  * are loaded and by calls to the {@code defineClass} method in the class
    48  * loader.
    49  *
    50  * <p> The following example uses a {@code Class} object to print the
    51  * class name of an object:
    52  *
    53  * <p> <blockquote><pre>
    54  *     void printClassName(Object obj) {
    55  *         System.out.println("The class of " + obj +
    56  *                            " is " + obj.getClass().getName());
    57  *     }
    58  * </pre></blockquote>
    59  *
    60  * <p> It is also possible to get the {@code Class} object for a named
    61  * type (or for void) using a class literal.  See Section 15.8.2 of
    62  * <cite>The Java&trade; Language Specification</cite>.
    63  * For example:
    64  *
    65  * <p> <blockquote>
    66  *     {@code System.out.println("The name of class Foo is: "+Foo.class.getName());}
    67  * </blockquote>
    68  *
    69  * @param <T> the type of the class modeled by this {@code Class}
    70  * object.  For example, the type of {@code String.class} is {@code
    71  * Class<String>}.  Use {@code Class<?>} if the class being modeled is
    72  * unknown.
    73  *
    74  * @author  unascribed
    75  * @see     java.lang.ClassLoader#defineClass(byte[], int, int)
    76  * @since   JDK1.0
    77  */
    78 public final
    79     class Class<T> implements java.io.Serializable,
    80                               java.lang.reflect.GenericDeclaration,
    81                               java.lang.reflect.Type,
    82                               java.lang.reflect.AnnotatedElement {
    83     private static final int ANNOTATION= 0x00002000;
    84     private static final int ENUM      = 0x00004000;
    85     private static final int SYNTHETIC = 0x00001000;
    86 
    87     /*
    88      * Constructor. Only the Java Virtual Machine creates Class
    89      * objects.
    90      */
    91     private Class() {}
    92 
    93 
    94     /**
    95      * Converts the object to a string. The string representation is the
    96      * string "class" or "interface", followed by a space, and then by the
    97      * fully qualified name of the class in the format returned by
    98      * {@code getName}.  If this {@code Class} object represents a
    99      * primitive type, this method returns the name of the primitive type.  If
   100      * this {@code Class} object represents void this method returns
   101      * "void".
   102      *
   103      * @return a string representation of this class object.
   104      */
   105     public String toString() {
   106         return (isInterface() ? "interface " : (isPrimitive() ? "" : "class "))
   107             + getName();
   108     }
   109 
   110 
   111     /**
   112      * Returns the {@code Class} object associated with the class or
   113      * interface with the given string name.  Invoking this method is
   114      * equivalent to:
   115      *
   116      * <blockquote>
   117      *  {@code Class.forName(className, true, currentLoader)}
   118      * </blockquote>
   119      *
   120      * where {@code currentLoader} denotes the defining class loader of
   121      * the current class.
   122      *
   123      * <p> For example, the following code fragment returns the
   124      * runtime {@code Class} descriptor for the class named
   125      * {@code java.lang.Thread}:
   126      *
   127      * <blockquote>
   128      *   {@code Class t = Class.forName("java.lang.Thread")}
   129      * </blockquote>
   130      * <p>
   131      * A call to {@code forName("X")} causes the class named
   132      * {@code X} to be initialized.
   133      *
   134      * @param      className   the fully qualified name of the desired class.
   135      * @return     the {@code Class} object for the class with the
   136      *             specified name.
   137      * @exception LinkageError if the linkage fails
   138      * @exception ExceptionInInitializerError if the initialization provoked
   139      *            by this method fails
   140      * @exception ClassNotFoundException if the class cannot be located
   141      */
   142     public static Class<?> forName(String className)
   143                 throws ClassNotFoundException {
   144         throw new UnsupportedOperationException();
   145     }
   146 
   147 
   148     /**
   149      * Creates a new instance of the class represented by this {@code Class}
   150      * object.  The class is instantiated as if by a {@code new}
   151      * expression with an empty argument list.  The class is initialized if it
   152      * has not already been initialized.
   153      *
   154      * <p>Note that this method propagates any exception thrown by the
   155      * nullary constructor, including a checked exception.  Use of
   156      * this method effectively bypasses the compile-time exception
   157      * checking that would otherwise be performed by the compiler.
   158      * The {@link
   159      * java.lang.reflect.Constructor#newInstance(java.lang.Object...)
   160      * Constructor.newInstance} method avoids this problem by wrapping
   161      * any exception thrown by the constructor in a (checked) {@link
   162      * java.lang.reflect.InvocationTargetException}.
   163      *
   164      * @return     a newly allocated instance of the class represented by this
   165      *             object.
   166      * @exception  IllegalAccessException  if the class or its nullary
   167      *               constructor is not accessible.
   168      * @exception  InstantiationException
   169      *               if this {@code Class} represents an abstract class,
   170      *               an interface, an array class, a primitive type, or void;
   171      *               or if the class has no nullary constructor;
   172      *               or if the instantiation fails for some other reason.
   173      * @exception  ExceptionInInitializerError if the initialization
   174      *               provoked by this method fails.
   175      * @exception  SecurityException
   176      *             If a security manager, <i>s</i>, is present and any of the
   177      *             following conditions is met:
   178      *
   179      *             <ul>
   180      *
   181      *             <li> invocation of
   182      *             {@link SecurityManager#checkMemberAccess
   183      *             s.checkMemberAccess(this, Member.PUBLIC)} denies
   184      *             creation of new instances of this class
   185      *
   186      *             <li> the caller's class loader is not the same as or an
   187      *             ancestor of the class loader for the current class and
   188      *             invocation of {@link SecurityManager#checkPackageAccess
   189      *             s.checkPackageAccess()} denies access to the package
   190      *             of this class
   191      *
   192      *             </ul>
   193      *
   194      */
   195     @JavaScriptBody(args = "self", body =
   196           "var inst = self.cnstr();"
   197         + "inst.cons__V(inst);"
   198         + "return inst;"
   199     )
   200     public T newInstance()
   201         throws InstantiationException, IllegalAccessException
   202     {
   203         throw new UnsupportedOperationException();
   204     }
   205 
   206     /**
   207      * Determines if the specified {@code Object} is assignment-compatible
   208      * with the object represented by this {@code Class}.  This method is
   209      * the dynamic equivalent of the Java language {@code instanceof}
   210      * operator. The method returns {@code true} if the specified
   211      * {@code Object} argument is non-null and can be cast to the
   212      * reference type represented by this {@code Class} object without
   213      * raising a {@code ClassCastException.} It returns {@code false}
   214      * otherwise.
   215      *
   216      * <p> Specifically, if this {@code Class} object represents a
   217      * declared class, this method returns {@code true} if the specified
   218      * {@code Object} argument is an instance of the represented class (or
   219      * of any of its subclasses); it returns {@code false} otherwise. If
   220      * this {@code Class} object represents an array class, this method
   221      * returns {@code true} if the specified {@code Object} argument
   222      * can be converted to an object of the array class by an identity
   223      * conversion or by a widening reference conversion; it returns
   224      * {@code false} otherwise. If this {@code Class} object
   225      * represents an interface, this method returns {@code true} if the
   226      * class or any superclass of the specified {@code Object} argument
   227      * implements this interface; it returns {@code false} otherwise. If
   228      * this {@code Class} object represents a primitive type, this method
   229      * returns {@code false}.
   230      *
   231      * @param   obj the object to check
   232      * @return  true if {@code obj} is an instance of this class
   233      *
   234      * @since JDK1.1
   235      */
   236     public native boolean isInstance(Object obj);
   237 
   238 
   239     /**
   240      * Determines if the class or interface represented by this
   241      * {@code Class} object is either the same as, or is a superclass or
   242      * superinterface of, the class or interface represented by the specified
   243      * {@code Class} parameter. It returns {@code true} if so;
   244      * otherwise it returns {@code false}. If this {@code Class}
   245      * object represents a primitive type, this method returns
   246      * {@code true} if the specified {@code Class} parameter is
   247      * exactly this {@code Class} object; otherwise it returns
   248      * {@code false}.
   249      *
   250      * <p> Specifically, this method tests whether the type represented by the
   251      * specified {@code Class} parameter can be converted to the type
   252      * represented by this {@code Class} object via an identity conversion
   253      * or via a widening reference conversion. See <em>The Java Language
   254      * Specification</em>, sections 5.1.1 and 5.1.4 , for details.
   255      *
   256      * @param cls the {@code Class} object to be checked
   257      * @return the {@code boolean} value indicating whether objects of the
   258      * type {@code cls} can be assigned to objects of this class
   259      * @exception NullPointerException if the specified Class parameter is
   260      *            null.
   261      * @since JDK1.1
   262      */
   263     public native boolean isAssignableFrom(Class<?> cls);
   264 
   265 
   266     /**
   267      * Determines if the specified {@code Class} object represents an
   268      * interface type.
   269      *
   270      * @return  {@code true} if this object represents an interface;
   271      *          {@code false} otherwise.
   272      */
   273     public native boolean isInterface();
   274 
   275 
   276     /**
   277      * Determines if this {@code Class} object represents an array class.
   278      *
   279      * @return  {@code true} if this object represents an array class;
   280      *          {@code false} otherwise.
   281      * @since   JDK1.1
   282      */
   283     public boolean isArray() {
   284         return false;
   285     }
   286 
   287 
   288     /**
   289      * Determines if the specified {@code Class} object represents a
   290      * primitive type.
   291      *
   292      * <p> There are nine predefined {@code Class} objects to represent
   293      * the eight primitive types and void.  These are created by the Java
   294      * Virtual Machine, and have the same names as the primitive types that
   295      * they represent, namely {@code boolean}, {@code byte},
   296      * {@code char}, {@code short}, {@code int},
   297      * {@code long}, {@code float}, and {@code double}.
   298      *
   299      * <p> These objects may only be accessed via the following public static
   300      * final variables, and are the only {@code Class} objects for which
   301      * this method returns {@code true}.
   302      *
   303      * @return true if and only if this class represents a primitive type
   304      *
   305      * @see     java.lang.Boolean#TYPE
   306      * @see     java.lang.Character#TYPE
   307      * @see     java.lang.Byte#TYPE
   308      * @see     java.lang.Short#TYPE
   309      * @see     java.lang.Integer#TYPE
   310      * @see     java.lang.Long#TYPE
   311      * @see     java.lang.Float#TYPE
   312      * @see     java.lang.Double#TYPE
   313      * @see     java.lang.Void#TYPE
   314      * @since JDK1.1
   315      */
   316     public native boolean isPrimitive();
   317 
   318     /**
   319      * Returns true if this {@code Class} object represents an annotation
   320      * type.  Note that if this method returns true, {@link #isInterface()}
   321      * would also return true, as all annotation types are also interfaces.
   322      *
   323      * @return {@code true} if this class object represents an annotation
   324      *      type; {@code false} otherwise
   325      * @since 1.5
   326      */
   327     public boolean isAnnotation() {
   328         return (getModifiers() & ANNOTATION) != 0;
   329     }
   330 
   331     /**
   332      * Returns {@code true} if this class is a synthetic class;
   333      * returns {@code false} otherwise.
   334      * @return {@code true} if and only if this class is a synthetic class as
   335      *         defined by the Java Language Specification.
   336      * @since 1.5
   337      */
   338     public boolean isSynthetic() {
   339         return (getModifiers() & SYNTHETIC) != 0;
   340     }
   341 
   342     /**
   343      * Returns the  name of the entity (class, interface, array class,
   344      * primitive type, or void) represented by this {@code Class} object,
   345      * as a {@code String}.
   346      *
   347      * <p> If this class object represents a reference type that is not an
   348      * array type then the binary name of the class is returned, as specified
   349      * by
   350      * <cite>The Java&trade; Language Specification</cite>.
   351      *
   352      * <p> If this class object represents a primitive type or void, then the
   353      * name returned is a {@code String} equal to the Java language
   354      * keyword corresponding to the primitive type or void.
   355      *
   356      * <p> If this class object represents a class of arrays, then the internal
   357      * form of the name consists of the name of the element type preceded by
   358      * one or more '{@code [}' characters representing the depth of the array
   359      * nesting.  The encoding of element type names is as follows:
   360      *
   361      * <blockquote><table summary="Element types and encodings">
   362      * <tr><th> Element Type <th> &nbsp;&nbsp;&nbsp; <th> Encoding
   363      * <tr><td> boolean      <td> &nbsp;&nbsp;&nbsp; <td align=center> Z
   364      * <tr><td> byte         <td> &nbsp;&nbsp;&nbsp; <td align=center> B
   365      * <tr><td> char         <td> &nbsp;&nbsp;&nbsp; <td align=center> C
   366      * <tr><td> class or interface
   367      *                       <td> &nbsp;&nbsp;&nbsp; <td align=center> L<i>classname</i>;
   368      * <tr><td> double       <td> &nbsp;&nbsp;&nbsp; <td align=center> D
   369      * <tr><td> float        <td> &nbsp;&nbsp;&nbsp; <td align=center> F
   370      * <tr><td> int          <td> &nbsp;&nbsp;&nbsp; <td align=center> I
   371      * <tr><td> long         <td> &nbsp;&nbsp;&nbsp; <td align=center> J
   372      * <tr><td> short        <td> &nbsp;&nbsp;&nbsp; <td align=center> S
   373      * </table></blockquote>
   374      *
   375      * <p> The class or interface name <i>classname</i> is the binary name of
   376      * the class specified above.
   377      *
   378      * <p> Examples:
   379      * <blockquote><pre>
   380      * String.class.getName()
   381      *     returns "java.lang.String"
   382      * byte.class.getName()
   383      *     returns "byte"
   384      * (new Object[3]).getClass().getName()
   385      *     returns "[Ljava.lang.Object;"
   386      * (new int[3][4][5][6][7][8][9]).getClass().getName()
   387      *     returns "[[[[[[[I"
   388      * </pre></blockquote>
   389      *
   390      * @return  the name of the class or interface
   391      *          represented by this object.
   392      */
   393     public String getName() {
   394         return jvmName().replace('/', '.');
   395     }
   396 
   397     @JavaScriptBody(args = "self", body = "return self.jvmName;")
   398     private native String jvmName();
   399 
   400     
   401     /**
   402      * Returns an array of {@code TypeVariable} objects that represent the
   403      * type variables declared by the generic declaration represented by this
   404      * {@code GenericDeclaration} object, in declaration order.  Returns an
   405      * array of length 0 if the underlying generic declaration declares no type
   406      * variables.
   407      *
   408      * @return an array of {@code TypeVariable} objects that represent
   409      *     the type variables declared by this generic declaration
   410      * @throws java.lang.reflect.GenericSignatureFormatError if the generic
   411      *     signature of this generic declaration does not conform to
   412      *     the format specified in
   413      *     <cite>The Java&trade; Virtual Machine Specification</cite>
   414      * @since 1.5
   415      */
   416     public TypeVariable<Class<T>>[] getTypeParameters() {
   417         throw new UnsupportedOperationException();
   418     }
   419  
   420     /**
   421      * Returns the {@code Class} representing the superclass of the entity
   422      * (class, interface, primitive type or void) represented by this
   423      * {@code Class}.  If this {@code Class} represents either the
   424      * {@code Object} class, an interface, a primitive type, or void, then
   425      * null is returned.  If this object represents an array class then the
   426      * {@code Class} object representing the {@code Object} class is
   427      * returned.
   428      *
   429      * @return the superclass of the class represented by this object.
   430      */
   431     @JavaScriptBody(args = "self", body = "return self.superclass;")
   432     public native Class<? super T> getSuperclass();
   433 
   434     /**
   435      * Returns the Java language modifiers for this class or interface, encoded
   436      * in an integer. The modifiers consist of the Java Virtual Machine's
   437      * constants for {@code public}, {@code protected},
   438      * {@code private}, {@code final}, {@code static},
   439      * {@code abstract} and {@code interface}; they should be decoded
   440      * using the methods of class {@code Modifier}.
   441      *
   442      * <p> If the underlying class is an array class, then its
   443      * {@code public}, {@code private} and {@code protected}
   444      * modifiers are the same as those of its component type.  If this
   445      * {@code Class} represents a primitive type or void, its
   446      * {@code public} modifier is always {@code true}, and its
   447      * {@code protected} and {@code private} modifiers are always
   448      * {@code false}. If this object represents an array class, a
   449      * primitive type or void, then its {@code final} modifier is always
   450      * {@code true} and its interface modifier is always
   451      * {@code false}. The values of its other modifiers are not determined
   452      * by this specification.
   453      *
   454      * <p> The modifier encodings are defined in <em>The Java Virtual Machine
   455      * Specification</em>, table 4.1.
   456      *
   457      * @return the {@code int} representing the modifiers for this class
   458      * @see     java.lang.reflect.Modifier
   459      * @since JDK1.1
   460      */
   461     public native int getModifiers();
   462 
   463 
   464     /**
   465      * Returns the simple name of the underlying class as given in the
   466      * source code. Returns an empty string if the underlying class is
   467      * anonymous.
   468      *
   469      * <p>The simple name of an array is the simple name of the
   470      * component type with "[]" appended.  In particular the simple
   471      * name of an array whose component type is anonymous is "[]".
   472      *
   473      * @return the simple name of the underlying class
   474      * @since 1.5
   475      */
   476     public String getSimpleName() {
   477         if (isArray())
   478             return getComponentType().getSimpleName()+"[]";
   479 
   480         String simpleName = getSimpleBinaryName();
   481         if (simpleName == null) { // top level class
   482             simpleName = getName();
   483             return simpleName.substring(simpleName.lastIndexOf(".")+1); // strip the package name
   484         }
   485         // According to JLS3 "Binary Compatibility" (13.1) the binary
   486         // name of non-package classes (not top level) is the binary
   487         // name of the immediately enclosing class followed by a '$' followed by:
   488         // (for nested and inner classes): the simple name.
   489         // (for local classes): 1 or more digits followed by the simple name.
   490         // (for anonymous classes): 1 or more digits.
   491 
   492         // Since getSimpleBinaryName() will strip the binary name of
   493         // the immediatly enclosing class, we are now looking at a
   494         // string that matches the regular expression "\$[0-9]*"
   495         // followed by a simple name (considering the simple of an
   496         // anonymous class to be the empty string).
   497 
   498         // Remove leading "\$[0-9]*" from the name
   499         int length = simpleName.length();
   500         if (length < 1 || simpleName.charAt(0) != '$')
   501             throw new IllegalStateException("Malformed class name");
   502         int index = 1;
   503         while (index < length && isAsciiDigit(simpleName.charAt(index)))
   504             index++;
   505         // Eventually, this is the empty string iff this is an anonymous class
   506         return simpleName.substring(index);
   507     }
   508 
   509     /**
   510      * Returns the "simple binary name" of the underlying class, i.e.,
   511      * the binary name without the leading enclosing class name.
   512      * Returns {@code null} if the underlying class is a top level
   513      * class.
   514      */
   515     private String getSimpleBinaryName() {
   516         Class<?> enclosingClass = null; // XXX getEnclosingClass();
   517         if (enclosingClass == null) // top level class
   518             return null;
   519         // Otherwise, strip the enclosing class' name
   520         try {
   521             return getName().substring(enclosingClass.getName().length());
   522         } catch (IndexOutOfBoundsException ex) {
   523             throw new IllegalStateException("Malformed class name");
   524         }
   525     }
   526     
   527     /**
   528      * Character.isDigit answers {@code true} to some non-ascii
   529      * digits.  This one does not.
   530      */
   531     private static boolean isAsciiDigit(char c) {
   532         return '0' <= c && c <= '9';
   533     }
   534 
   535     /**
   536      * Returns the canonical name of the underlying class as
   537      * defined by the Java Language Specification.  Returns null if
   538      * the underlying class does not have a canonical name (i.e., if
   539      * it is a local or anonymous class or an array whose component
   540      * type does not have a canonical name).
   541      * @return the canonical name of the underlying class if it exists, and
   542      * {@code null} otherwise.
   543      * @since 1.5
   544      */
   545     public String getCanonicalName() {
   546         if (isArray()) {
   547             String canonicalName = getComponentType().getCanonicalName();
   548             if (canonicalName != null)
   549                 return canonicalName + "[]";
   550             else
   551                 return null;
   552         }
   553 //        if (isLocalOrAnonymousClass())
   554 //            return null;
   555 //        Class<?> enclosingClass = getEnclosingClass();
   556         Class<?> enclosingClass = null;
   557         if (enclosingClass == null) { // top level class
   558             return getName();
   559         } else {
   560             String enclosingName = enclosingClass.getCanonicalName();
   561             if (enclosingName == null)
   562                 return null;
   563             return enclosingName + "." + getSimpleName();
   564         }
   565     }
   566 
   567     /**
   568      * Finds a resource with a given name.  The rules for searching resources
   569      * associated with a given class are implemented by the defining
   570      * {@linkplain ClassLoader class loader} of the class.  This method
   571      * delegates to this object's class loader.  If this object was loaded by
   572      * the bootstrap class loader, the method delegates to {@link
   573      * ClassLoader#getSystemResourceAsStream}.
   574      *
   575      * <p> Before delegation, an absolute resource name is constructed from the
   576      * given resource name using this algorithm:
   577      *
   578      * <ul>
   579      *
   580      * <li> If the {@code name} begins with a {@code '/'}
   581      * (<tt>'&#92;u002f'</tt>), then the absolute name of the resource is the
   582      * portion of the {@code name} following the {@code '/'}.
   583      *
   584      * <li> Otherwise, the absolute name is of the following form:
   585      *
   586      * <blockquote>
   587      *   {@code modified_package_name/name}
   588      * </blockquote>
   589      *
   590      * <p> Where the {@code modified_package_name} is the package name of this
   591      * object with {@code '/'} substituted for {@code '.'}
   592      * (<tt>'&#92;u002e'</tt>).
   593      *
   594      * </ul>
   595      *
   596      * @param  name name of the desired resource
   597      * @return      A {@link java.io.InputStream} object or {@code null} if
   598      *              no resource with this name is found
   599      * @throws  NullPointerException If {@code name} is {@code null}
   600      * @since  JDK1.1
   601      */
   602      public InputStream getResourceAsStream(String name) {
   603         name = resolveName(name);
   604         ClassLoader cl = getClassLoader0();
   605         if (cl==null) {
   606             // A system class.
   607             return ClassLoader.getSystemResourceAsStream(name);
   608         }
   609         return cl.getResourceAsStream(name);
   610     }
   611 
   612     /**
   613      * Finds a resource with a given name.  The rules for searching resources
   614      * associated with a given class are implemented by the defining
   615      * {@linkplain ClassLoader class loader} of the class.  This method
   616      * delegates to this object's class loader.  If this object was loaded by
   617      * the bootstrap class loader, the method delegates to {@link
   618      * ClassLoader#getSystemResource}.
   619      *
   620      * <p> Before delegation, an absolute resource name is constructed from the
   621      * given resource name using this algorithm:
   622      *
   623      * <ul>
   624      *
   625      * <li> If the {@code name} begins with a {@code '/'}
   626      * (<tt>'&#92;u002f'</tt>), then the absolute name of the resource is the
   627      * portion of the {@code name} following the {@code '/'}.
   628      *
   629      * <li> Otherwise, the absolute name is of the following form:
   630      *
   631      * <blockquote>
   632      *   {@code modified_package_name/name}
   633      * </blockquote>
   634      *
   635      * <p> Where the {@code modified_package_name} is the package name of this
   636      * object with {@code '/'} substituted for {@code '.'}
   637      * (<tt>'&#92;u002e'</tt>).
   638      *
   639      * </ul>
   640      *
   641      * @param  name name of the desired resource
   642      * @return      A  {@link java.net.URL} object or {@code null} if no
   643      *              resource with this name is found
   644      * @since  JDK1.1
   645      */
   646     public java.net.URL getResource(String name) {
   647         name = resolveName(name);
   648         ClassLoader cl = getClassLoader0();
   649         if (cl==null) {
   650             // A system class.
   651             return ClassLoader.getSystemResource(name);
   652         }
   653         return cl.getResource(name);
   654     }
   655 
   656 
   657    /**
   658      * Add a package name prefix if the name is not absolute Remove leading "/"
   659      * if name is absolute
   660      */
   661     private String resolveName(String name) {
   662         if (name == null) {
   663             return name;
   664         }
   665         if (!name.startsWith("/")) {
   666             Class<?> c = this;
   667             while (c.isArray()) {
   668                 c = c.getComponentType();
   669             }
   670             String baseName = c.getName();
   671             int index = baseName.lastIndexOf('.');
   672             if (index != -1) {
   673                 name = baseName.substring(0, index).replace('.', '/')
   674                     +"/"+name;
   675             }
   676         } else {
   677             name = name.substring(1);
   678         }
   679         return name;
   680     }
   681     
   682     /**
   683      * Returns the class loader for the class.  Some implementations may use
   684      * null to represent the bootstrap class loader. This method will return
   685      * null in such implementations if this class was loaded by the bootstrap
   686      * class loader.
   687      *
   688      * <p> If a security manager is present, and the caller's class loader is
   689      * not null and the caller's class loader is not the same as or an ancestor of
   690      * the class loader for the class whose class loader is requested, then
   691      * this method calls the security manager's {@code checkPermission}
   692      * method with a {@code RuntimePermission("getClassLoader")}
   693      * permission to ensure it's ok to access the class loader for the class.
   694      *
   695      * <p>If this object
   696      * represents a primitive type or void, null is returned.
   697      *
   698      * @return  the class loader that loaded the class or interface
   699      *          represented by this object.
   700      * @throws SecurityException
   701      *    if a security manager exists and its
   702      *    {@code checkPermission} method denies
   703      *    access to the class loader for the class.
   704      * @see java.lang.ClassLoader
   705      * @see SecurityManager#checkPermission
   706      * @see java.lang.RuntimePermission
   707      */
   708     public ClassLoader getClassLoader() {
   709         throw new SecurityException();
   710     }
   711     
   712     // Package-private to allow ClassLoader access
   713     native ClassLoader getClassLoader0();    
   714 
   715     /**
   716      * Returns the {@code Class} representing the component type of an
   717      * array.  If this class does not represent an array class this method
   718      * returns null.
   719      *
   720      * @return the {@code Class} representing the component type of this
   721      * class if this class is an array
   722      * @see     java.lang.reflect.Array
   723      * @since JDK1.1
   724      */
   725     public Class<?> getComponentType() {
   726         return null;
   727     }
   728 
   729     /**
   730      * Returns true if and only if this class was declared as an enum in the
   731      * source code.
   732      *
   733      * @return true if and only if this class was declared as an enum in the
   734      *     source code
   735      * @since 1.5
   736      */
   737     public boolean isEnum() {
   738         // An enum must both directly extend java.lang.Enum and have
   739         // the ENUM bit set; classes for specialized enum constants
   740         // don't do the former.
   741         return (this.getModifiers() & ENUM) != 0 &&
   742         this.getSuperclass() == java.lang.Enum.class;
   743     }
   744 
   745     /**
   746      * Casts an object to the class or interface represented
   747      * by this {@code Class} object.
   748      *
   749      * @param obj the object to be cast
   750      * @return the object after casting, or null if obj is null
   751      *
   752      * @throws ClassCastException if the object is not
   753      * null and is not assignable to the type T.
   754      *
   755      * @since 1.5
   756      */
   757     public T cast(Object obj) {
   758         if (obj != null && !isInstance(obj))
   759             throw new ClassCastException(cannotCastMsg(obj));
   760         return (T) obj;
   761     }
   762 
   763     private String cannotCastMsg(Object obj) {
   764         return "Cannot cast " + obj.getClass().getName() + " to " + getName();
   765     }
   766 
   767     /**
   768      * Casts this {@code Class} object to represent a subclass of the class
   769      * represented by the specified class object.  Checks that that the cast
   770      * is valid, and throws a {@code ClassCastException} if it is not.  If
   771      * this method succeeds, it always returns a reference to this class object.
   772      *
   773      * <p>This method is useful when a client needs to "narrow" the type of
   774      * a {@code Class} object to pass it to an API that restricts the
   775      * {@code Class} objects that it is willing to accept.  A cast would
   776      * generate a compile-time warning, as the correctness of the cast
   777      * could not be checked at runtime (because generic types are implemented
   778      * by erasure).
   779      *
   780      * @return this {@code Class} object, cast to represent a subclass of
   781      *    the specified class object.
   782      * @throws ClassCastException if this {@code Class} object does not
   783      *    represent a subclass of the specified class (here "subclass" includes
   784      *    the class itself).
   785      * @since 1.5
   786      */
   787     public <U> Class<? extends U> asSubclass(Class<U> clazz) {
   788         if (clazz.isAssignableFrom(this))
   789             return (Class<? extends U>) this;
   790         else
   791             throw new ClassCastException(this.toString());
   792     }
   793 
   794     @JavaScriptBody(args = { "self", "ac" }, 
   795         body = 
   796           "if (self.anno) {"
   797         + "  return self.anno['L' + ac.jvmName + ';'];"
   798         + "}"
   799     )
   800     private Object getAnnotationData(Class<?> annotationClass) {
   801         throw new UnsupportedOperationException();
   802     }
   803     /**
   804      * @throws NullPointerException {@inheritDoc}
   805      * @since 1.5
   806      */
   807     public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {
   808         Object data = getAnnotationData(annotationClass);
   809         return data == null ? null : AnnotationImpl.create(annotationClass, data);
   810     }
   811 
   812     /**
   813      * @throws NullPointerException {@inheritDoc}
   814      * @since 1.5
   815      */
   816     @JavaScriptBody(args = { "self", "ac" }, 
   817         body = "if (self.anno && self.anno['L' + ac.jvmName + ';']) { return true; }"
   818         + "else return false;"
   819     )
   820     public boolean isAnnotationPresent(
   821         Class<? extends Annotation> annotationClass) {
   822         if (annotationClass == null)
   823             throw new NullPointerException();
   824 
   825         return getAnnotation(annotationClass) != null;
   826     }
   827 
   828     @JavaScriptBody(args = "self", body = "return self.anno;")
   829     private Object getAnnotationData() {
   830         throw new UnsupportedOperationException();
   831     }
   832 
   833     /**
   834      * @since 1.5
   835      */
   836     public Annotation[] getAnnotations() {
   837         Object data = getAnnotationData();
   838         return data == null ? new Annotation[0] : AnnotationImpl.create(data);
   839     }
   840 
   841     /**
   842      * @since 1.5
   843      */
   844     public Annotation[] getDeclaredAnnotations()  {
   845         throw new UnsupportedOperationException();
   846     }
   847 
   848     static Class getPrimitiveClass(String type) {
   849         // XXX
   850         return Object.class;
   851     }
   852 
   853     public boolean desiredAssertionStatus() {
   854         return false;
   855     }
   856 }