< prev index next >

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

Print this page




2238      *          ancestor of the class loader for the current class and
2239      *          invocation of {@link SecurityManager#checkPackageAccess
2240      *          s.checkPackageAccess()} denies access to the package
2241      *          of this class
2242      *
2243      *          </ul>
2244      *
2245      * @since 1.1
2246      * @jls 8.2 Class Members
2247      * @jls 8.3 Field Declarations
2248      */
2249     @CallerSensitive
2250     public Field[] getDeclaredFields() throws SecurityException {
2251         SecurityManager sm = System.getSecurityManager();
2252         if (sm != null) {
2253             checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);
2254         }
2255         return copyFields(privateGetDeclaredFields(false));
2256     }
2257 























2258 
2259     /**
2260      * Returns an array containing {@code Method} objects reflecting all the
2261      * declared methods of the class or interface represented by this {@code
2262      * Class} object, including public, protected, default (package)
2263      * access, and private methods, but excluding inherited methods.
2264      *
2265      * <p> If this {@code Class} object represents a type that has multiple
2266      * declared methods with the same name and parameter types, but different
2267      * return types, then the returned array has a {@code Method} object for
2268      * each such method.
2269      *
2270      * <p> If this {@code Class} object represents a type that has a class
2271      * initialization method {@code <clinit>}, then the returned array does
2272      * <em>not</em> have a corresponding {@code Method} object.
2273      *
2274      * <p> If this {@code Class} object represents a class or interface with no
2275      * declared methods, then the returned array has length 0.
2276      *
2277      * <p> If this {@code Class} object represents an array type, a primitive


2939         }
2940     }
2941 
2942     /**
2943      * Reflection support.
2944      */
2945 
2946     // Reflection data caches various derived names and reflective members. Cached
2947     // values may be invalidated when JVM TI RedefineClasses() is called
2948     private static class ReflectionData<T> {
2949         volatile Field[] declaredFields;
2950         volatile Field[] publicFields;
2951         volatile Method[] declaredMethods;
2952         volatile Method[] publicMethods;
2953         volatile Constructor<T>[] declaredConstructors;
2954         volatile Constructor<T>[] publicConstructors;
2955         // Intermediate results for getFields and getMethods
2956         volatile Field[] declaredPublicFields;
2957         volatile Method[] declaredPublicMethods;
2958         volatile Class<?>[] interfaces;


2959 
2960         // Cached names
2961         String simpleName;
2962         String canonicalName;
2963         static final String NULL_SENTINEL = new String();
2964 
2965         // Value of classRedefinedCount when we created this ReflectionData instance
2966         final int redefinedCount;
2967 
2968         ReflectionData(int redefinedCount) {
2969             this.redefinedCount = redefinedCount;
2970         }
2971     }
2972 
2973     private transient volatile SoftReference<ReflectionData<T>> reflectionData;
2974 
2975     // Incremented by the VM on each call to JVM TI RedefineClasses()
2976     // that redefines this class or a superclass.
2977     private transient volatile int classRedefinedCount;
2978 


3059     // via ReflectionFactory.copyField.
3060     private Field[] privateGetDeclaredFields(boolean publicOnly) {
3061         Field[] res;
3062         ReflectionData<T> rd = reflectionData();
3063         if (rd != null) {
3064             res = publicOnly ? rd.declaredPublicFields : rd.declaredFields;
3065             if (res != null) return res;
3066         }
3067         // No cached value available; request value from VM
3068         res = Reflection.filterFields(this, getDeclaredFields0(publicOnly));
3069         if (rd != null) {
3070             if (publicOnly) {
3071                 rd.declaredPublicFields = res;
3072             } else {
3073                 rd.declaredFields = res;
3074             }
3075         }
3076         return res;
3077     }
3078 















3079     // Returns an array of "root" fields. These Field objects must NOT
3080     // be propagated to the outside world, but must instead be copied
3081     // via ReflectionFactory.copyField.
3082     private Field[] privateGetPublicFields() {
3083         Field[] res;
3084         ReflectionData<T> rd = reflectionData();
3085         if (rd != null) {
3086             res = rd.publicFields;
3087             if (res != null) return res;
3088         }
3089 
3090         // Use a linked hash set to ensure order is preserved and
3091         // fields from common super interfaces are not duplicated
3092         LinkedHashSet<Field> fields = new LinkedHashSet<>();
3093 
3094         // Local fields
3095         addAll(fields, privateGetDeclaredFields(true));
3096 
3097         // Direct superinterfaces, recursively
3098         for (Class<?> si : getInterfaces()) {


3396         ReflectionFactory fact = getReflectionFactory();
3397         for (int i = 0; i < arg.length; i++) {
3398             out[i] = fact.copyMethod(arg[i]);
3399         }
3400         return out;
3401     }
3402 
3403     private static <U> Constructor<U>[] copyConstructors(Constructor<U>[] arg) {
3404         Constructor<U>[] out = arg.clone();
3405         ReflectionFactory fact = getReflectionFactory();
3406         for (int i = 0; i < out.length; i++) {
3407             out[i] = fact.copyConstructor(out[i]);
3408         }
3409         return out;
3410     }
3411 
3412     private native Field[]       getDeclaredFields0(boolean publicOnly);
3413     private native Method[]      getDeclaredMethods0(boolean publicOnly);
3414     private native Constructor<T>[] getDeclaredConstructors0(boolean publicOnly);
3415     private native Class<?>[]   getDeclaredClasses0();


3416 
3417     /**
3418      * Helper method to get the method name from arguments.
3419      */
3420     private String methodToString(String name, Class<?>[] argTypes) {
3421         StringBuilder sb = new StringBuilder();
3422         sb.append(getName() + "." + name + "(");
3423         if (argTypes != null) {
3424             sb.append(Arrays.stream(argTypes)
3425                       .map(c -> (c == null) ? "null" : c.getName())
3426                       .collect(Collectors.joining(",")));
3427         }
3428         sb.append(")");
3429         return sb.toString();
3430     }
3431 
3432     /** use serialVersionUID from JDK 1.1 for interoperability */
3433     private static final long serialVersionUID = 3206093459760846163L;
3434 
3435 


3493         return desiredAssertionStatus0(this);
3494     }
3495 
3496     // Retrieves the desired assertion status of this class from the VM
3497     private static native boolean desiredAssertionStatus0(Class<?> clazz);
3498 
3499     /**
3500      * Returns true if and only if this class was declared as an enum in the
3501      * source code.
3502      *
3503      * @return true if and only if this class was declared as an enum in the
3504      *     source code
3505      * @since 1.5
3506      */
3507     public boolean isEnum() {
3508         // An enum must both directly extend java.lang.Enum and have
3509         // the ENUM bit set; classes for specialized enum constants
3510         // don't do the former.
3511         return (this.getModifiers() & ENUM) != 0 &&
3512         this.getSuperclass() == java.lang.Enum.class;























































3513     }
3514 
3515     // Fetches the factory for reflective objects
3516     private static ReflectionFactory getReflectionFactory() {
3517         if (reflectionFactory == null) {
3518             reflectionFactory =
3519                 java.security.AccessController.doPrivileged
3520                     (new ReflectionFactory.GetReflectionFactoryAction());
3521         }
3522         return reflectionFactory;
3523     }
3524     private static ReflectionFactory reflectionFactory;
3525 
3526     /**
3527      * Returns the elements of this enum class or null if this
3528      * Class object does not represent an enum type.
3529      *
3530      * @return an array containing the values comprising the enum class
3531      *     represented by this Class object in the order they're
3532      *     declared, or null if this Class object does not




2238      *          ancestor of the class loader for the current class and
2239      *          invocation of {@link SecurityManager#checkPackageAccess
2240      *          s.checkPackageAccess()} denies access to the package
2241      *          of this class
2242      *
2243      *          </ul>
2244      *
2245      * @since 1.1
2246      * @jls 8.2 Class Members
2247      * @jls 8.3 Field Declarations
2248      */
2249     @CallerSensitive
2250     public Field[] getDeclaredFields() throws SecurityException {
2251         SecurityManager sm = System.getSecurityManager();
2252         if (sm != null) {
2253             checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);
2254         }
2255         return copyFields(privateGetDeclaredFields(false));
2256     }
2257 
2258     /**
2259      * TBD
2260      * @return TBD
2261      * @throws SecurityException TBD
2262      * @since 1.12
2263      */
2264     @CallerSensitive
2265     public Field[] getRecordParameters() throws SecurityException {
2266         SecurityManager sm = System.getSecurityManager();
2267         if (sm != null) {
2268             checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);
2269         }
2270         return isPrimitive() || isArray() ? new Field[0] : copyFields(privateGetRecordParameters());
2271     }
2272 
2273     /**
2274      * Returns the number of record parameters if this class is a record, 0 if not
2275      * @return the number of record parameters
2276      * @since 1.12
2277      */
2278     public int getRecordParametersCount() {
2279         return isPrimitive() || isArray() ? 0 : getRecordParametersCount0();
2280     }
2281 
2282     /**
2283      * Returns an array containing {@code Method} objects reflecting all the
2284      * declared methods of the class or interface represented by this {@code
2285      * Class} object, including public, protected, default (package)
2286      * access, and private methods, but excluding inherited methods.
2287      *
2288      * <p> If this {@code Class} object represents a type that has multiple
2289      * declared methods with the same name and parameter types, but different
2290      * return types, then the returned array has a {@code Method} object for
2291      * each such method.
2292      *
2293      * <p> If this {@code Class} object represents a type that has a class
2294      * initialization method {@code <clinit>}, then the returned array does
2295      * <em>not</em> have a corresponding {@code Method} object.
2296      *
2297      * <p> If this {@code Class} object represents a class or interface with no
2298      * declared methods, then the returned array has length 0.
2299      *
2300      * <p> If this {@code Class} object represents an array type, a primitive


2962         }
2963     }
2964 
2965     /**
2966      * Reflection support.
2967      */
2968 
2969     // Reflection data caches various derived names and reflective members. Cached
2970     // values may be invalidated when JVM TI RedefineClasses() is called
2971     private static class ReflectionData<T> {
2972         volatile Field[] declaredFields;
2973         volatile Field[] publicFields;
2974         volatile Method[] declaredMethods;
2975         volatile Method[] publicMethods;
2976         volatile Constructor<T>[] declaredConstructors;
2977         volatile Constructor<T>[] publicConstructors;
2978         // Intermediate results for getFields and getMethods
2979         volatile Field[] declaredPublicFields;
2980         volatile Method[] declaredPublicMethods;
2981         volatile Class<?>[] interfaces;
2982         // record parameters
2983         volatile Field[] recordParameters;
2984 
2985         // Cached names
2986         String simpleName;
2987         String canonicalName;
2988         static final String NULL_SENTINEL = new String();
2989 
2990         // Value of classRedefinedCount when we created this ReflectionData instance
2991         final int redefinedCount;
2992 
2993         ReflectionData(int redefinedCount) {
2994             this.redefinedCount = redefinedCount;
2995         }
2996     }
2997 
2998     private transient volatile SoftReference<ReflectionData<T>> reflectionData;
2999 
3000     // Incremented by the VM on each call to JVM TI RedefineClasses()
3001     // that redefines this class or a superclass.
3002     private transient volatile int classRedefinedCount;
3003 


3084     // via ReflectionFactory.copyField.
3085     private Field[] privateGetDeclaredFields(boolean publicOnly) {
3086         Field[] res;
3087         ReflectionData<T> rd = reflectionData();
3088         if (rd != null) {
3089             res = publicOnly ? rd.declaredPublicFields : rd.declaredFields;
3090             if (res != null) return res;
3091         }
3092         // No cached value available; request value from VM
3093         res = Reflection.filterFields(this, getDeclaredFields0(publicOnly));
3094         if (rd != null) {
3095             if (publicOnly) {
3096                 rd.declaredPublicFields = res;
3097             } else {
3098                 rd.declaredFields = res;
3099             }
3100         }
3101         return res;
3102     }
3103 
3104     private Field[] privateGetRecordParameters() {
3105         Field[] res;
3106         ReflectionData<T> rd = reflectionData();
3107         if (rd != null) {
3108             res = rd.recordParameters;
3109             if (res != null) return res;
3110         }
3111         // No cached value available; request value from VM
3112         res = Reflection.filterFields(this, getRecordParameters0());
3113         if (rd != null) {
3114             rd.recordParameters = res;
3115         }
3116         return res;
3117     }
3118 
3119     // Returns an array of "root" fields. These Field objects must NOT
3120     // be propagated to the outside world, but must instead be copied
3121     // via ReflectionFactory.copyField.
3122     private Field[] privateGetPublicFields() {
3123         Field[] res;
3124         ReflectionData<T> rd = reflectionData();
3125         if (rd != null) {
3126             res = rd.publicFields;
3127             if (res != null) return res;
3128         }
3129 
3130         // Use a linked hash set to ensure order is preserved and
3131         // fields from common super interfaces are not duplicated
3132         LinkedHashSet<Field> fields = new LinkedHashSet<>();
3133 
3134         // Local fields
3135         addAll(fields, privateGetDeclaredFields(true));
3136 
3137         // Direct superinterfaces, recursively
3138         for (Class<?> si : getInterfaces()) {


3436         ReflectionFactory fact = getReflectionFactory();
3437         for (int i = 0; i < arg.length; i++) {
3438             out[i] = fact.copyMethod(arg[i]);
3439         }
3440         return out;
3441     }
3442 
3443     private static <U> Constructor<U>[] copyConstructors(Constructor<U>[] arg) {
3444         Constructor<U>[] out = arg.clone();
3445         ReflectionFactory fact = getReflectionFactory();
3446         for (int i = 0; i < out.length; i++) {
3447             out[i] = fact.copyConstructor(out[i]);
3448         }
3449         return out;
3450     }
3451 
3452     private native Field[]       getDeclaredFields0(boolean publicOnly);
3453     private native Method[]      getDeclaredMethods0(boolean publicOnly);
3454     private native Constructor<T>[] getDeclaredConstructors0(boolean publicOnly);
3455     private native Class<?>[]   getDeclaredClasses0();
3456     private native Field[]      getRecordParameters0();
3457     private native int          getRecordParametersCount0();
3458 
3459     /**
3460      * Helper method to get the method name from arguments.
3461      */
3462     private String methodToString(String name, Class<?>[] argTypes) {
3463         StringBuilder sb = new StringBuilder();
3464         sb.append(getName() + "." + name + "(");
3465         if (argTypes != null) {
3466             sb.append(Arrays.stream(argTypes)
3467                       .map(c -> (c == null) ? "null" : c.getName())
3468                       .collect(Collectors.joining(",")));
3469         }
3470         sb.append(")");
3471         return sb.toString();
3472     }
3473 
3474     /** use serialVersionUID from JDK 1.1 for interoperability */
3475     private static final long serialVersionUID = 3206093459760846163L;
3476 
3477 


3535         return desiredAssertionStatus0(this);
3536     }
3537 
3538     // Retrieves the desired assertion status of this class from the VM
3539     private static native boolean desiredAssertionStatus0(Class<?> clazz);
3540 
3541     /**
3542      * Returns true if and only if this class was declared as an enum in the
3543      * source code.
3544      *
3545      * @return true if and only if this class was declared as an enum in the
3546      *     source code
3547      * @since 1.5
3548      */
3549     public boolean isEnum() {
3550         // An enum must both directly extend java.lang.Enum and have
3551         // the ENUM bit set; classes for specialized enum constants
3552         // don't do the former.
3553         return (this.getModifiers() & ENUM) != 0 &&
3554         this.getSuperclass() == java.lang.Enum.class;
3555     }
3556 
3557     /**
3558      * Returns true if and only if this class was declared as a record in the
3559      * source code.
3560      *
3561      * @return true if and only if this class was declared as a record in the
3562      *     source code
3563      * @since 1.12
3564      */
3565     public boolean isRecord() {
3566         // A record must directly extend java.lang.AbstractRecord
3567         return AbstractRecord.class.isAssignableFrom(this);
3568     }
3569 
3570     /**
3571      * Returns an array with the names of the components
3572      *
3573      * @return an array with the names of the components
3574      * @since 1.12
3575      */
3576     public String[] getRecordParameterNames() {
3577         if (isRecord()) {
3578             Field[] recordParameters = getRecordParameters();
3579             String[] names = new String[recordParameters.length];
3580             int i = 0;
3581             for (Field field : recordParameters) {
3582                 names[i] = field.getName();
3583                 i++;
3584             }
3585             return names;
3586         } else {
3587             return new String[0];
3588         }
3589     }
3590 
3591     /**
3592      * Returns an array with the types of the record parameters
3593      *
3594      * @return an array with the types of the record parameters
3595      * @since 1.12
3596      */
3597     public Class<?>[] getRecordParameterTypes() {
3598         if (isRecord()) {
3599             Field[] recordParameters = getRecordParameters();
3600             Class<?>[] types = new Class<?>[recordParameters.length];
3601             int i = 0;
3602             for (Field field : recordParameters) {
3603                 types[i] = field.getType();
3604                 i++;
3605             }
3606             return types;
3607         } else {
3608             return new Class<?>[0];
3609         }
3610     }
3611 
3612     // Fetches the factory for reflective objects
3613     private static ReflectionFactory getReflectionFactory() {
3614         if (reflectionFactory == null) {
3615             reflectionFactory =
3616                 java.security.AccessController.doPrivileged
3617                     (new ReflectionFactory.GetReflectionFactoryAction());
3618         }
3619         return reflectionFactory;
3620     }
3621     private static ReflectionFactory reflectionFactory;
3622 
3623     /**
3624      * Returns the elements of this enum class or null if this
3625      * Class object does not represent an enum type.
3626      *
3627      * @return an array containing the values comprising the enum class
3628      *     represented by this Class object in the order they're
3629      *     declared, or null if this Class object does not


< prev index next >