< prev index next >

src/java.base/share/classes/java/lang/Class.java

Print this page
rev 58565 : 8238358: Implementation of JEP 371: Hidden Classes
Reviewed-by: duke
Contributed-by: mandy.chung@oracle.com, lois.foltan@oracle.com, david.holmes@oracle.com, harold.seigel@oracle.com, serguei.spitsyn@oracle.com, alex.buckley@oracle.com, jamsheed.c.m@oracle.com


  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.lang.annotation.Annotation;
  29 import java.lang.constant.ClassDesc;
  30 import java.lang.invoke.TypeDescriptor;

  31 import java.lang.module.ModuleReader;
  32 import java.lang.ref.SoftReference;
  33 import java.io.IOException;
  34 import java.io.InputStream;
  35 import java.io.ObjectStreamField;
  36 import java.lang.reflect.AnnotatedElement;
  37 import java.lang.reflect.AnnotatedType;
  38 import java.lang.reflect.Array;
  39 import java.lang.reflect.Constructor;
  40 import java.lang.reflect.Executable;
  41 import java.lang.reflect.Field;
  42 import java.lang.reflect.GenericArrayType;
  43 import java.lang.reflect.GenericDeclaration;
  44 import java.lang.reflect.InvocationTargetException;
  45 import java.lang.reflect.Member;
  46 import java.lang.reflect.Method;
  47 import java.lang.reflect.Modifier;
  48 import java.lang.reflect.Proxy;
  49 import java.lang.reflect.RecordComponent;
  50 import java.lang.reflect.Type;
  51 import java.lang.reflect.TypeVariable;
  52 import java.lang.constant.Constable;
  53 import java.net.URL;
  54 import java.security.AccessController;
  55 import java.security.PrivilegedAction;
  56 import java.util.ArrayList;
  57 import java.util.Arrays;
  58 import java.util.Collection;
  59 import java.util.HashMap;
  60 import java.util.LinkedHashMap;
  61 import java.util.LinkedHashSet;
  62 import java.util.List;
  63 import java.util.Map;
  64 import java.util.Objects;
  65 import java.util.Optional;
  66 import java.util.StringJoiner;
  67 import java.util.stream.Stream;
  68 import java.util.stream.Collectors;
  69 
  70 import jdk.internal.HotSpotIntrinsicCandidate;
  71 import jdk.internal.loader.BootLoader;
  72 import jdk.internal.loader.BuiltinClassLoader;
  73 import jdk.internal.misc.Unsafe;
  74 import jdk.internal.module.Resources;
  75 import jdk.internal.reflect.CallerSensitive;
  76 import jdk.internal.reflect.ConstantPool;
  77 import jdk.internal.reflect.Reflection;
  78 import jdk.internal.reflect.ReflectionFactory;
  79 import jdk.internal.vm.annotation.ForceInline;
  80 import sun.invoke.util.Wrapper;
  81 import sun.reflect.generics.factory.CoreReflectionFactory;
  82 import sun.reflect.generics.factory.GenericsFactory;
  83 import sun.reflect.generics.repository.ClassRepository;
  84 import sun.reflect.generics.repository.MethodRepository;
  85 import sun.reflect.generics.repository.ConstructorRepository;
  86 import sun.reflect.generics.scope.ClassScope;
  87 import sun.security.util.SecurityConstants;


 111  * characteristics are determined by the class loading environment at run time,
 112  * such as the module returned by {@link #getModule() getModule()}.
 113  *
 114  * <p> Some methods of class {@code Class} expose whether the declaration of
 115  * a class or interface in Java source code was <em>enclosed</em> within
 116  * another declaration. Other methods describe how a class or interface
 117  * is situated in a <em>nest</em>. A <a id="nest">nest</a> is a set of
 118  * classes and interfaces, in the same run-time package, that
 119  * allow mutual access to their {@code private} members.
 120  * The classes and interfaces are known as <em>nestmates</em>.
 121  * One nestmate acts as the
 122  * <em>nest host</em>, and enumerates the other nestmates which
 123  * belong to the nest; each of them in turn records it as the nest host.
 124  * The classes and interfaces which belong to a nest, including its host, are
 125  * determined when
 126  * {@code class} files are generated, for example, a Java compiler
 127  * will typically record a top-level class as the host of a nest where the
 128  * other members are the classes and interfaces whose declarations are
 129  * enclosed within the top-level class declaration.
 130  *





 131  * <p> The following example uses a {@code Class} object to print the
 132  * class name of an object:
 133  *
 134  * <blockquote><pre>
 135  *     void printClassName(Object obj) {
 136  *         System.out.println("The class of " + obj +
 137  *                            " is " + obj.getClass().getName());
 138  *     }
 139  * </pre></blockquote>
 140  *
 141  * <p> It is also possible to get the {@code Class} object for a named
 142  * type (or for void) using a class literal.  See Section 15.8.2 of
 143  * <cite>The Java&trade; Language Specification</cite>.
 144  * For example:
 145  *
 146  * <blockquote>
 147  *     {@code System.out.println("The name of class Foo is: "+Foo.class.getName());}
 148  * </blockquote>
 149  *
 150  * @param <T> the type of the class modeled by this {@code Class}


 789      * <tr><th scope="row"> long         <td style="text-align:center"> J
 790      * <tr><th scope="row"> short        <td style="text-align:center"> S
 791      * </tbody>
 792      * </table></blockquote>
 793      *
 794      * <p> The class or interface name <i>classname</i> is the binary name of
 795      * the class specified above.
 796      *
 797      * <p> Examples:
 798      * <blockquote><pre>
 799      * String.class.getName()
 800      *     returns "java.lang.String"
 801      * byte.class.getName()
 802      *     returns "byte"
 803      * (new Object[3]).getClass().getName()
 804      *     returns "[Ljava.lang.Object;"
 805      * (new int[3][4][5][6][7][8][9]).getClass().getName()
 806      *     returns "[[[[[[[I"
 807      * </pre></blockquote>
 808      *




 809      * @return  the name of the class or interface
 810      *          represented by this object.
 811      */
 812     public String getName() {
 813         String name = this.name;
 814         return name != null ? name : initClassName();
 815     }
 816 
 817     // Cache the name to reduce the number of calls into the VM.
 818     // This field would be set by VM itself during initClassName call.
 819     private transient String name;
 820     private native String initClassName();
 821 
 822     /**
 823      * Returns the class loader for the class.  Some implementations may use
 824      * null to represent the bootstrap class loader. This method will return
 825      * null in such implementations if this class was loaded by the bootstrap
 826      * class loader.
 827      *
 828      * <p>If this object


 868      * ClassLoader#getUnnamedModule() unnamed} {@code Module} of the class
 869      * loader for this class is returned.
 870      *
 871      * @return the module that this class or interface is a member of
 872      *
 873      * @since 9
 874      * @spec JPMS
 875      */
 876     public Module getModule() {
 877         return module;
 878     }
 879 
 880     // set by VM
 881     private transient Module module;
 882 
 883     // Initialized in JVM not by private constructor
 884     // This field is filtered from reflection access, i.e. getDeclaredField
 885     // will throw NoSuchFieldException
 886     private final ClassLoader classLoader;
 887 








 888     /**
 889      * Returns an array of {@code TypeVariable} objects that represent the
 890      * type variables declared by the generic declaration represented by this
 891      * {@code GenericDeclaration} object, in declaration order.  Returns an
 892      * array of length 0 if the underlying generic declaration declares no type
 893      * variables.
 894      *
 895      * @return an array of {@code TypeVariable} objects that represent
 896      *     the type variables declared by this generic declaration
 897      * @throws java.lang.reflect.GenericSignatureFormatError if the generic
 898      *     signature of this generic declaration does not conform to
 899      *     the format specified in
 900      *     <cite>The Java&trade; Virtual Machine Specification</cite>
 901      * @since 1.5
 902      */
 903     @SuppressWarnings("unchecked")
 904     public TypeVariable<Class<T>>[] getTypeParameters() {
 905         ClassRepository info = getGenericInfo();
 906         if (info != null)
 907             return (TypeVariable<Class<T>>[])info.getTypeParameters();


1619      * {@code null} otherwise.
1620      * @since 1.5
1621      */
1622     public String getCanonicalName() {
1623         ReflectionData<T> rd = reflectionData();
1624         String canonicalName = rd.canonicalName;
1625         if (canonicalName == null) {
1626             rd.canonicalName = canonicalName = getCanonicalName0();
1627         }
1628         return canonicalName == ReflectionData.NULL_SENTINEL? null : canonicalName;
1629     }
1630 
1631     private String getCanonicalName0() {
1632         if (isArray()) {
1633             String canonicalName = getComponentType().getCanonicalName();
1634             if (canonicalName != null)
1635                 return canonicalName + "[]";
1636             else
1637                 return ReflectionData.NULL_SENTINEL;
1638         }
1639         if (isLocalOrAnonymousClass())
1640             return ReflectionData.NULL_SENTINEL;
1641         Class<?> enclosingClass = getEnclosingClass();
1642         if (enclosingClass == null) { // top level class
1643             return getName();
1644         } else {
1645             String enclosingName = enclosingClass.getCanonicalName();
1646             if (enclosingName == null)
1647                 return ReflectionData.NULL_SENTINEL;
1648             return enclosingName + "." + getSimpleName();
1649         }
1650     }
1651 
1652     /**
1653      * Returns {@code true} if and only if the underlying class
1654      * is an anonymous class.

1655      *
1656      * @return {@code true} if and only if this class is an anonymous class.
1657      * @since 1.5
1658      */
1659     public boolean isAnonymousClass() {
1660         return !isArray() && isLocalOrAnonymousClass() &&
1661                 getSimpleBinaryName0() == null;
1662     }
1663 
1664     /**
1665      * Returns {@code true} if and only if the underlying class
1666      * is a local class.
1667      *
1668      * @return {@code true} if and only if this class is a local class.
1669      * @since 1.5
1670      */
1671     public boolean isLocalClass() {
1672         return isLocalOrAnonymousClass() &&
1673                 (isArray() || getSimpleBinaryName0() != null);
1674     }


2859      * ensure it's ok to get the
2860      * {@code ProtectionDomain}.
2861      *
2862      * @return the ProtectionDomain of this class
2863      *
2864      * @throws SecurityException
2865      *        if a security manager exists and its
2866      *        {@code checkPermission} method doesn't allow
2867      *        getting the ProtectionDomain.
2868      *
2869      * @see java.security.ProtectionDomain
2870      * @see SecurityManager#checkPermission
2871      * @see java.lang.RuntimePermission
2872      * @since 1.2
2873      */
2874     public java.security.ProtectionDomain getProtectionDomain() {
2875         SecurityManager sm = System.getSecurityManager();
2876         if (sm != null) {
2877             sm.checkPermission(SecurityConstants.GET_PD_PERMISSION);
2878         }





2879         java.security.ProtectionDomain pd = getProtectionDomain0();
2880         if (pd == null) {
2881             if (allPermDomain == null) {
2882                 java.security.Permissions perms =
2883                     new java.security.Permissions();
2884                 perms.add(SecurityConstants.ALL_PERMISSION);
2885                 allPermDomain =
2886                     new java.security.ProtectionDomain(null, perms);
2887             }
2888             pd = allPermDomain;
2889         }
2890         return pd;
2891     }
2892 
2893 
2894     /**
2895      * Returns the ProtectionDomain of this class.
2896      */
2897     private native java.security.ProtectionDomain getProtectionDomain0();
2898 
2899     /*
2900      * Return the Virtual Machine's Class object for the named
2901      * primitive type.
2902      */
2903     static native Class<?> getPrimitiveClass(String name);
2904 
2905     /*
2906      * Check if client is allowed to access members.  If access is denied,
2907      * throw a SecurityException.
2908      *
2909      * This method also enforces package access.
2910      *
2911      * <p> Default policy: allow all clients access with normal Java access
2912      * control.
2913      *


3991      * <p> If this {@code Class} object represents a class or interface whose
3992      * declaration does not explicitly indicate any annotated superinterfaces,
3993      * the return value is an array of length 0.
3994      *
3995      * <p> If this {@code Class} object represents either the {@code Object}
3996      * class, an array type, a primitive type, or void, the return value is an
3997      * array of length 0.
3998      *
3999      * @return an array representing the superinterfaces
4000      * @since 1.8
4001      */
4002     public AnnotatedType[] getAnnotatedInterfaces() {
4003          return TypeAnnotationParser.buildAnnotatedInterfaces(getRawTypeAnnotations(), getConstantPool(), this);
4004     }
4005 
4006     private native Class<?> getNestHost0();
4007 
4008     /**
4009      * Returns the nest host of the <a href=#nest>nest</a> to which the class
4010      * or interface represented by this {@code Class} object belongs.
4011      * Every class and interface is a member of exactly one nest.
4012      * A class or interface that is not recorded as belonging to a nest
4013      * belongs to the nest consisting only of itself, and is the nest
4014      * host.
4015      *
4016      * <p>Each of the {@code Class} objects representing array types,
4017      * primitive types, and {@code void} returns {@code this} to indicate
4018      * that the represented entity belongs to the nest consisting only of
4019      * itself, and is the nest host.
4020      *
4021      * <p>If there is a {@linkplain LinkageError linkage error} accessing
4022      * the nest host, or if this class or interface is not enumerated as
4023      * a member of the nest by the nest host, then it is considered to belong
4024      * to its own nest and {@code this} is returned as the host.
4025      *
4026      * @apiNote A {@code class} file of version 55.0 or greater may record the
4027      * host of the nest to which it belongs by using the {@code NestHost}
4028      * attribute (JVMS 4.7.28). Alternatively, a {@code class} file of
4029      * version 55.0 or greater may act as a nest host by enumerating the nest's
4030      * other members with the
4031      * {@code NestMembers} attribute (JVMS 4.7.29).
4032      * A {@code class} file of version 54.0 or lower does not use these
4033      * attributes.

4034      *
4035      * @return the nest host of this class or interface
4036      *
4037      * @throws SecurityException
4038      *         If the returned class is not the current class, and
4039      *         if a security manager, <i>s</i>, is present and the caller's
4040      *         class loader is not the same as or an ancestor of the class
4041      *         loader for the returned class and invocation of {@link
4042      *         SecurityManager#checkPackageAccess s.checkPackageAccess()}
4043      *         denies access to the package of the returned class
4044      * @since 11
4045      * @jvms 4.7.28 The {@code NestHost} Attribute
4046      * @jvms 4.7.29 The {@code NestMembers} Attribute
4047      * @jvms 5.4.4 Access Control
4048      */
4049     @CallerSensitive
4050     public Class<?> getNestHost() {
4051         if (isPrimitive() || isArray()) {
4052             return this;
4053         }
4054         Class<?> host;
4055         try {
4056             host = getNestHost0();
4057         } catch (LinkageError e) {
4058             // if we couldn't load our nest-host then we
4059             // act as-if we have no nest-host attribute
4060             return this;
4061         }
4062         // if null then nest membership validation failed, so we
4063         // act as-if we have no nest-host attribute
4064         if (host == null || host == this) {
4065             return this;
4066         }
4067         // returning a different class requires a security check
4068         SecurityManager sm = System.getSecurityManager();
4069         if (sm != null) {
4070             checkPackageAccess(sm,
4071                                ClassLoader.getClassLoader(Reflection.getCallerClass()), true);
4072         }
4073         return host;
4074     }
4075 
4076     /**
4077      * Determines if the given {@code Class} is a nestmate of the
4078      * class or interface represented by this {@code Class} object.
4079      * Two classes or interfaces are nestmates
4080      * if they have the same {@linkplain #getNestHost() nest host}.
4081      *
4082      * @param c the class to check
4083      * @return {@code true} if this class and {@code c} are members of
4084      * the same nest; and {@code false} otherwise.
4085      *
4086      * @since 11
4087      */
4088     public boolean isNestmateOf(Class<?> c) {
4089         if (this == c) {
4090             return true;
4091         }
4092         if (isPrimitive() || isArray() ||
4093             c.isPrimitive() || c.isArray()) {
4094             return false;
4095         }
4096         try {
4097             return getNestHost0() == c.getNestHost0();
4098         } catch (LinkageError e) {
4099             return false;
4100         }
4101     }
4102 
4103     private native Class<?>[] getNestMembers0();
4104 
4105     /**
4106      * Returns an array containing {@code Class} objects representing all the
4107      * classes and interfaces that are members of the nest to which the class
4108      * or interface represented by this {@code Class} object belongs.
4109      * The {@linkplain #getNestHost() nest host} of that nest is the zeroth
4110      * element of the array. Subsequent elements represent any classes or
4111      * interfaces that are recorded by the nest host as being members of
4112      * the nest; the order of such elements is unspecified. Duplicates are
4113      * permitted.
4114      * If the nest host of that nest does not enumerate any members, then the
4115      * array has a single element containing {@code this}.
4116      *
4117      * <p>Each of the {@code Class} objects representing array types,
4118      * primitive types, and {@code void} returns an array containing only













4119      * {@code this}.
4120      *
4121      * <p>This method validates that, for each class or interface which is
4122      * recorded as a member of the nest by the nest host, that class or
4123      * interface records itself as a member of that same nest. Any exceptions
4124      * that occur during this validation are rethrown by this method.

4125      *
4126      * @return an array of all classes and interfaces in the same nest as
4127      * this class
4128      *
4129      * @throws LinkageError
4130      *         If there is any problem loading or validating a nest member or
4131      *         its nest host
4132      * @throws SecurityException
4133      *         If any returned class is not the current class, and
4134      *         if a security manager, <i>s</i>, is present and the caller's
4135      *         class loader is not the same as or an ancestor of the class
4136      *         loader for that returned class and invocation of {@link
4137      *         SecurityManager#checkPackageAccess s.checkPackageAccess()}
4138      *         denies access to the package of that returned class
4139      *
4140      * @since 11
4141      * @see #getNestHost()


4142      */
4143     @CallerSensitive
4144     public Class<?>[] getNestMembers() {
4145         if (isPrimitive() || isArray()) {
4146             return new Class<?>[] { this };
4147         }
4148         Class<?>[] members = getNestMembers0();
4149         // Can't actually enable this due to bootstrapping issues
4150         // assert(members.length != 1 || members[0] == this); // expected invariant from VM
4151 
4152         if (members.length > 1) {
4153             // If we return anything other than the current class we need
4154             // a security check
4155             SecurityManager sm = System.getSecurityManager();
4156             if (sm != null) {
4157                 checkPackageAccess(sm,
4158                                    ClassLoader.getClassLoader(Reflection.getCallerClass()), true);
4159             }
4160         }
4161         return members;


4207      * @return a {@code Class} describing the array type
4208      * @since 12
4209      */
4210     @Override
4211     public Class<?> arrayType() {
4212         return Array.newInstance(this, 0).getClass();
4213     }
4214 
4215     /**
4216      * Returns a nominal descriptor for this instance, if one can be
4217      * constructed, or an empty {@link Optional} if one cannot be.
4218      *
4219      * @return An {@link Optional} containing the resulting nominal descriptor,
4220      * or an empty {@link Optional} if one cannot be constructed.
4221      * @since 12
4222      */
4223     @Override
4224     public Optional<ClassDesc> describeConstable() {
4225         return Optional.of(ClassDesc.ofDescriptor(descriptorString()));
4226     }


















4227 }


  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.lang.annotation.Annotation;
  29 import java.lang.constant.ClassDesc;
  30 import java.lang.invoke.TypeDescriptor;
  31 import java.lang.invoke.MethodHandles;
  32 import java.lang.module.ModuleReader;
  33 import java.lang.ref.SoftReference;
  34 import java.io.IOException;
  35 import java.io.InputStream;
  36 import java.io.ObjectStreamField;
  37 import java.lang.reflect.AnnotatedElement;
  38 import java.lang.reflect.AnnotatedType;
  39 import java.lang.reflect.Array;
  40 import java.lang.reflect.Constructor;
  41 import java.lang.reflect.Executable;
  42 import java.lang.reflect.Field;
  43 import java.lang.reflect.GenericArrayType;
  44 import java.lang.reflect.GenericDeclaration;
  45 import java.lang.reflect.InvocationTargetException;
  46 import java.lang.reflect.Member;
  47 import java.lang.reflect.Method;
  48 import java.lang.reflect.Modifier;
  49 import java.lang.reflect.Proxy;
  50 import java.lang.reflect.RecordComponent;
  51 import java.lang.reflect.Type;
  52 import java.lang.reflect.TypeVariable;
  53 import java.lang.constant.Constable;
  54 import java.net.URL;
  55 import java.security.AccessController;
  56 import java.security.PrivilegedAction;
  57 import java.util.ArrayList;
  58 import java.util.Arrays;
  59 import java.util.Collection;
  60 import java.util.HashMap;
  61 import java.util.LinkedHashMap;
  62 import java.util.LinkedHashSet;
  63 import java.util.List;
  64 import java.util.Map;
  65 import java.util.Objects;
  66 import java.util.Optional;


  67 import java.util.stream.Collectors;
  68 
  69 import jdk.internal.HotSpotIntrinsicCandidate;
  70 import jdk.internal.loader.BootLoader;
  71 import jdk.internal.loader.BuiltinClassLoader;
  72 import jdk.internal.misc.Unsafe;
  73 import jdk.internal.module.Resources;
  74 import jdk.internal.reflect.CallerSensitive;
  75 import jdk.internal.reflect.ConstantPool;
  76 import jdk.internal.reflect.Reflection;
  77 import jdk.internal.reflect.ReflectionFactory;
  78 import jdk.internal.vm.annotation.ForceInline;
  79 import sun.invoke.util.Wrapper;
  80 import sun.reflect.generics.factory.CoreReflectionFactory;
  81 import sun.reflect.generics.factory.GenericsFactory;
  82 import sun.reflect.generics.repository.ClassRepository;
  83 import sun.reflect.generics.repository.MethodRepository;
  84 import sun.reflect.generics.repository.ConstructorRepository;
  85 import sun.reflect.generics.scope.ClassScope;
  86 import sun.security.util.SecurityConstants;


 110  * characteristics are determined by the class loading environment at run time,
 111  * such as the module returned by {@link #getModule() getModule()}.
 112  *
 113  * <p> Some methods of class {@code Class} expose whether the declaration of
 114  * a class or interface in Java source code was <em>enclosed</em> within
 115  * another declaration. Other methods describe how a class or interface
 116  * is situated in a <em>nest</em>. A <a id="nest">nest</a> is a set of
 117  * classes and interfaces, in the same run-time package, that
 118  * allow mutual access to their {@code private} members.
 119  * The classes and interfaces are known as <em>nestmates</em>.
 120  * One nestmate acts as the
 121  * <em>nest host</em>, and enumerates the other nestmates which
 122  * belong to the nest; each of them in turn records it as the nest host.
 123  * The classes and interfaces which belong to a nest, including its host, are
 124  * determined when
 125  * {@code class} files are generated, for example, a Java compiler
 126  * will typically record a top-level class as the host of a nest where the
 127  * other members are the classes and interfaces whose declarations are
 128  * enclosed within the top-level class declaration.
 129  *
 130  * <p> Some methods of class {@code Class} expose some characteristics of
 131  * <em>hidden classes</em>.  Hidden classes are created by calling
 132  * {@link java.lang.invoke.MethodHandles.Lookup#defineHiddenClass(byte[], boolean, MethodHandles.Lookup.ClassOption...)
 133  * Lookup::defineHiddenClass}.
 134  *
 135  * <p> The following example uses a {@code Class} object to print the
 136  * class name of an object:
 137  *
 138  * <blockquote><pre>
 139  *     void printClassName(Object obj) {
 140  *         System.out.println("The class of " + obj +
 141  *                            " is " + obj.getClass().getName());
 142  *     }
 143  * </pre></blockquote>
 144  *
 145  * <p> It is also possible to get the {@code Class} object for a named
 146  * type (or for void) using a class literal.  See Section 15.8.2 of
 147  * <cite>The Java&trade; Language Specification</cite>.
 148  * For example:
 149  *
 150  * <blockquote>
 151  *     {@code System.out.println("The name of class Foo is: "+Foo.class.getName());}
 152  * </blockquote>
 153  *
 154  * @param <T> the type of the class modeled by this {@code Class}


 793      * <tr><th scope="row"> long         <td style="text-align:center"> J
 794      * <tr><th scope="row"> short        <td style="text-align:center"> S
 795      * </tbody>
 796      * </table></blockquote>
 797      *
 798      * <p> The class or interface name <i>classname</i> is the binary name of
 799      * the class specified above.
 800      *
 801      * <p> Examples:
 802      * <blockquote><pre>
 803      * String.class.getName()
 804      *     returns "java.lang.String"
 805      * byte.class.getName()
 806      *     returns "byte"
 807      * (new Object[3]).getClass().getName()
 808      *     returns "[Ljava.lang.Object;"
 809      * (new int[3][4][5][6][7][8][9]).getClass().getName()
 810      *     returns "[[[[[[[I"
 811      * </pre></blockquote>
 812      *
 813      * <p> If this class object represents a {@linkplain #isHiddenClass() hidden class},
 814      * then the name of a hidden class is not a binary name and contains
 815      * a ASCII {@code '/'} character.
 816      *
 817      * @return  the name of the class or interface
 818      *          represented by this object.
 819      */
 820     public String getName() {
 821         String name = this.name;
 822         return name != null ? name : initClassName();
 823     }
 824 
 825     // Cache the name to reduce the number of calls into the VM.
 826     // This field would be set by VM itself during initClassName call.
 827     private transient String name;
 828     private native String initClassName();
 829 
 830     /**
 831      * Returns the class loader for the class.  Some implementations may use
 832      * null to represent the bootstrap class loader. This method will return
 833      * null in such implementations if this class was loaded by the bootstrap
 834      * class loader.
 835      *
 836      * <p>If this object


 876      * ClassLoader#getUnnamedModule() unnamed} {@code Module} of the class
 877      * loader for this class is returned.
 878      *
 879      * @return the module that this class or interface is a member of
 880      *
 881      * @since 9
 882      * @spec JPMS
 883      */
 884     public Module getModule() {
 885         return module;
 886     }
 887 
 888     // set by VM
 889     private transient Module module;
 890 
 891     // Initialized in JVM not by private constructor
 892     // This field is filtered from reflection access, i.e. getDeclaredField
 893     // will throw NoSuchFieldException
 894     private final ClassLoader classLoader;
 895 
 896     // Set by VM
 897     private transient Object classData;
 898 
 899     // package-private
 900     Object getClassData() {
 901         return classData;
 902     }
 903 
 904     /**
 905      * Returns an array of {@code TypeVariable} objects that represent the
 906      * type variables declared by the generic declaration represented by this
 907      * {@code GenericDeclaration} object, in declaration order.  Returns an
 908      * array of length 0 if the underlying generic declaration declares no type
 909      * variables.
 910      *
 911      * @return an array of {@code TypeVariable} objects that represent
 912      *     the type variables declared by this generic declaration
 913      * @throws java.lang.reflect.GenericSignatureFormatError if the generic
 914      *     signature of this generic declaration does not conform to
 915      *     the format specified in
 916      *     <cite>The Java&trade; Virtual Machine Specification</cite>
 917      * @since 1.5
 918      */
 919     @SuppressWarnings("unchecked")
 920     public TypeVariable<Class<T>>[] getTypeParameters() {
 921         ClassRepository info = getGenericInfo();
 922         if (info != null)
 923             return (TypeVariable<Class<T>>[])info.getTypeParameters();


1635      * {@code null} otherwise.
1636      * @since 1.5
1637      */
1638     public String getCanonicalName() {
1639         ReflectionData<T> rd = reflectionData();
1640         String canonicalName = rd.canonicalName;
1641         if (canonicalName == null) {
1642             rd.canonicalName = canonicalName = getCanonicalName0();
1643         }
1644         return canonicalName == ReflectionData.NULL_SENTINEL? null : canonicalName;
1645     }
1646 
1647     private String getCanonicalName0() {
1648         if (isArray()) {
1649             String canonicalName = getComponentType().getCanonicalName();
1650             if (canonicalName != null)
1651                 return canonicalName + "[]";
1652             else
1653                 return ReflectionData.NULL_SENTINEL;
1654         }
1655         if (isHiddenClass() || isLocalOrAnonymousClass())
1656             return ReflectionData.NULL_SENTINEL;
1657         Class<?> enclosingClass = getEnclosingClass();
1658         if (enclosingClass == null) { // top level class
1659             return getName();
1660         } else {
1661             String enclosingName = enclosingClass.getCanonicalName();
1662             if (enclosingName == null)
1663                 return ReflectionData.NULL_SENTINEL;
1664             return enclosingName + "." + getSimpleName();
1665         }
1666     }
1667 
1668     /**
1669      * Returns {@code true} if and only if the underlying class
1670      * is an anonymous class.  An anonymous class is not a
1671      * {@linkplain #isHiddenClass() hidden class}.
1672      *
1673      * @return {@code true} if and only if this class is an anonymous class.
1674      * @since 1.5
1675      */
1676     public boolean isAnonymousClass() {
1677         return !isArray() && isLocalOrAnonymousClass() &&
1678                 getSimpleBinaryName0() == null;
1679     }
1680 
1681     /**
1682      * Returns {@code true} if and only if the underlying class
1683      * is a local class.
1684      *
1685      * @return {@code true} if and only if this class is a local class.
1686      * @since 1.5
1687      */
1688     public boolean isLocalClass() {
1689         return isLocalOrAnonymousClass() &&
1690                 (isArray() || getSimpleBinaryName0() != null);
1691     }


2876      * ensure it's ok to get the
2877      * {@code ProtectionDomain}.
2878      *
2879      * @return the ProtectionDomain of this class
2880      *
2881      * @throws SecurityException
2882      *        if a security manager exists and its
2883      *        {@code checkPermission} method doesn't allow
2884      *        getting the ProtectionDomain.
2885      *
2886      * @see java.security.ProtectionDomain
2887      * @see SecurityManager#checkPermission
2888      * @see java.lang.RuntimePermission
2889      * @since 1.2
2890      */
2891     public java.security.ProtectionDomain getProtectionDomain() {
2892         SecurityManager sm = System.getSecurityManager();
2893         if (sm != null) {
2894             sm.checkPermission(SecurityConstants.GET_PD_PERMISSION);
2895         }
2896         return protectionDomain();
2897     }
2898 
2899     // package-private
2900     java.security.ProtectionDomain protectionDomain() {
2901         java.security.ProtectionDomain pd = getProtectionDomain0();
2902         if (pd == null) {
2903             if (allPermDomain == null) {
2904                 java.security.Permissions perms =
2905                     new java.security.Permissions();
2906                 perms.add(SecurityConstants.ALL_PERMISSION);
2907                 allPermDomain =
2908                     new java.security.ProtectionDomain(null, perms);
2909             }
2910             pd = allPermDomain;
2911         }
2912         return pd;
2913     }
2914 

2915     /**
2916      * Returns the ProtectionDomain of this class.
2917      */
2918     private native java.security.ProtectionDomain getProtectionDomain0();
2919 
2920     /*
2921      * Return the Virtual Machine's Class object for the named
2922      * primitive type.
2923      */
2924     static native Class<?> getPrimitiveClass(String name);
2925 
2926     /*
2927      * Check if client is allowed to access members.  If access is denied,
2928      * throw a SecurityException.
2929      *
2930      * This method also enforces package access.
2931      *
2932      * <p> Default policy: allow all clients access with normal Java access
2933      * control.
2934      *


4012      * <p> If this {@code Class} object represents a class or interface whose
4013      * declaration does not explicitly indicate any annotated superinterfaces,
4014      * the return value is an array of length 0.
4015      *
4016      * <p> If this {@code Class} object represents either the {@code Object}
4017      * class, an array type, a primitive type, or void, the return value is an
4018      * array of length 0.
4019      *
4020      * @return an array representing the superinterfaces
4021      * @since 1.8
4022      */
4023     public AnnotatedType[] getAnnotatedInterfaces() {
4024          return TypeAnnotationParser.buildAnnotatedInterfaces(getRawTypeAnnotations(), getConstantPool(), this);
4025     }
4026 
4027     private native Class<?> getNestHost0();
4028 
4029     /**
4030      * Returns the nest host of the <a href=#nest>nest</a> to which the class
4031      * or interface represented by this {@code Class} object belongs.
4032      * Every class and interface belongs to exactly one nest.








4033      *
4034      * If the nest host of this class or interface has previously
4035      * been determined, then this method returns the nest host.
4036      * If the nest host of this class or interface has
4037      * not previously been determined, then this method determines the nest
4038      * host using the algorithm of JVMS 5.4.4, and returns it.
4039      *
4040      * Often, a class or interface belongs to a nest consisting only of itself,
4041      * in which case this method returns {@code this} to indicate that the class
4042      * or interface is the nest host.
4043      *
4044      * <p>If this {@code Class} object represents a primitive type, an array type,
4045      * or {@code void}, then this method returns {@code this},
4046      * indicating that the represented entity belongs to the nest consisting only of
4047      * itself, and is the nest host.
4048      *
4049      * @return the nest host of this class or interface
4050      *
4051      * @throws SecurityException
4052      * If the returned class is not the current class, and
4053      * if a security manager, <i>s</i>, is present and the caller's
4054      * class loader is not the same as or an ancestor of the class
4055      * loader for the returned class and invocation of {@link
4056      * SecurityManager#checkPackageAccess s.checkPackageAccess()}
4057      * denies access to the package of the returned class
4058      * @since 11
4059      * @jvms 4.7.28 The {@code NestHost} Attribute
4060      * @jvms 4.7.29 The {@code NestMembers} Attribute
4061      * @jvms 5.4.4 Access Control
4062      */
4063     @CallerSensitive
4064     public Class<?> getNestHost() {
4065         if (isPrimitive() || isArray()) {
4066             return this;
4067         }
4068 
4069         Class<?> host = getNestHost0();
4070         if (host == this) {








4071             return this;
4072         }
4073         // returning a different class requires a security check
4074         SecurityManager sm = System.getSecurityManager();
4075         if (sm != null) {
4076             checkPackageAccess(sm,
4077                                ClassLoader.getClassLoader(Reflection.getCallerClass()), true);
4078         }
4079         return host;
4080     }
4081 
4082     /**
4083      * Determines if the given {@code Class} is a nestmate of the
4084      * class or interface represented by this {@code Class} object.
4085      * Two classes or interfaces are nestmates
4086      * if they have the same {@linkplain #getNestHost() nest host}.
4087      *
4088      * @param c the class to check
4089      * @return {@code true} if this class and {@code c} are members of
4090      * the same nest; and {@code false} otherwise.
4091      *
4092      * @since 11
4093      */
4094     public boolean isNestmateOf(Class<?> c) {
4095         if (this == c) {
4096             return true;
4097         }
4098         if (isPrimitive() || isArray() ||
4099             c.isPrimitive() || c.isArray()) {
4100             return false;
4101         }
4102 
4103         return getNestHost() == c.getNestHost();



4104     }
4105 
4106     private native Class<?>[] getNestMembers0();
4107 
4108     /**
4109      * Returns an array containing {@code Class} objects representing all the
4110      * classes and interfaces that are members of the nest to which the class
4111      * or interface represented by this {@code Class} object belongs.







4112      *
4113      * First, this method obtains the {@linkplain #getNestHost() nest host}, {@code H}, of the nest
4114      * to which the class or interface represented by this {@code Class} object belongs.
4115      * The zeroth element of the returned array is {@code H}.
4116      *
4117      * Then, for each class or interface {@code C} which is recorded by {@code H} as being a member
4118      * of its nest, this method attempts to obtain the {@code Class} object for {@code C}
4119      * (using {@linkplain #getClassLoader() the defining class loader} of the current {@code Class} object),
4120      * and then obtains the {@linkplain #getNestHost() nest host} of the nest to which {@code C} belongs.
4121      * The classes and interfaces which are recorded by {@code H} as being members of its nest,
4122      * and for which {@code H} can be determined as their nest host, are indicated by subsequent elements
4123      * of the returned array. The order of such elements is unspecified.
4124      * Duplicates are permitted.
4125      *
4126      * <p>If this {@code Class} object represents a primitive type, an array type,
4127      * or {@code void}, then this method returns a single-element array containing
4128      * {@code this}.
4129      *
4130      * @apiNote
4131      * The returned array includes only the nest members recorded in the {@code NestMembers}
4132      * attribute, and not any hidden classes that were added to the nest via
4133      * {@link MethodHandles.Lookup#defineHiddenClass(byte[], boolean, MethodHandles.Lookup.ClassOption...)
4134      * Lookup::defineHiddenClass}.
4135      *
4136      * @return an array of all classes and interfaces in the same nest as
4137      * this class
4138      *



4139      * @throws SecurityException
4140      * If any returned class is not the current class, and
4141      * if a security manager, <i>s</i>, is present and the caller's
4142      * class loader is not the same as or an ancestor of the class
4143      * loader for that returned class and invocation of {@link
4144      * SecurityManager#checkPackageAccess s.checkPackageAccess()}
4145      * denies access to the package of that returned class
4146      *
4147      * @since 11
4148      * @see #getNestHost()
4149      * @jvms 4.7.28 The {@code NestHost} Attribute
4150      * @jvms 4.7.29 The {@code NestMembers} Attribute
4151      */
4152     @CallerSensitive
4153     public Class<?>[] getNestMembers() {
4154         if (isPrimitive() || isArray()) {
4155             return new Class<?>[] { this };
4156         }
4157         Class<?>[] members = getNestMembers0();
4158         // Can't actually enable this due to bootstrapping issues
4159         // assert(members.length != 1 || members[0] == this); // expected invariant from VM
4160 
4161         if (members.length > 1) {
4162             // If we return anything other than the current class we need
4163             // a security check
4164             SecurityManager sm = System.getSecurityManager();
4165             if (sm != null) {
4166                 checkPackageAccess(sm,
4167                                    ClassLoader.getClassLoader(Reflection.getCallerClass()), true);
4168             }
4169         }
4170         return members;


4216      * @return a {@code Class} describing the array type
4217      * @since 12
4218      */
4219     @Override
4220     public Class<?> arrayType() {
4221         return Array.newInstance(this, 0).getClass();
4222     }
4223 
4224     /**
4225      * Returns a nominal descriptor for this instance, if one can be
4226      * constructed, or an empty {@link Optional} if one cannot be.
4227      *
4228      * @return An {@link Optional} containing the resulting nominal descriptor,
4229      * or an empty {@link Optional} if one cannot be constructed.
4230      * @since 12
4231      */
4232     @Override
4233     public Optional<ClassDesc> describeConstable() {
4234         return Optional.of(ClassDesc.ofDescriptor(descriptorString()));
4235    }
4236 
4237     /**
4238      * Returns {@code true} if and only if the underlying class is a hidden class.
4239      *
4240      * <p> A <em>hidden class</em> is created by calling
4241      * {@link MethodHandles.Lookup#defineHiddenClass(byte[], boolean, MethodHandles.Lookup.ClassOption...)
4242      * Lookup::defineHiddenClass}.   A hidden class is non-discoverable
4243      * by name via {@link Class#forName(String) Class::forName},
4244      * {@link ClassLoader#loadClass(String) ClassLoader::loadClass}, and bytecode linkage.
4245      *
4246      * @return {@code true} if and only if this class is a hidden class.
4247      *
4248      * @since 15
4249      * @see MethodHandles.Lookup#defineHiddenClass
4250      */
4251     @HotSpotIntrinsicCandidate
4252     public native boolean isHiddenClass();
4253 
4254 }
< prev index next >