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

Print this page




2381             return name;
2382         }
2383         if (!name.startsWith("/")) {
2384             Class<?> c = this;
2385             while (c.isArray()) {
2386                 c = c.getComponentType();
2387             }
2388             String baseName = c.getName();
2389             int index = baseName.lastIndexOf('.');
2390             if (index != -1) {
2391                 name = baseName.substring(0, index).replace('.', '/')
2392                     +"/"+name;
2393             }
2394         } else {
2395             name = name.substring(1);
2396         }
2397         return name;
2398     }
2399 
2400     /**







































2401      * Reflection support.
2402      */
2403 
2404     // Caches for certain reflective results
2405     private static boolean useCaches = true;
2406 
2407     // reflection data that might get invalidated when JVM TI RedefineClasses() is called
2408     static class ReflectionData<T> {
2409         volatile Field[] declaredFields;
2410         volatile Field[] publicFields;
2411         volatile Method[] declaredMethods;
2412         volatile Method[] publicMethods;
2413         volatile Constructor<T>[] declaredConstructors;
2414         volatile Constructor<T>[] publicConstructors;
2415         // Intermediate results for getFields and getMethods
2416         volatile Field[] declaredPublicFields;
2417         volatile Method[] declaredPublicMethods;
2418         volatile Class<?>[] interfaces;
2419 
2420         // Value of classRedefinedCount when we created this ReflectionData instance
2421         final int redefinedCount;
2422 
2423         ReflectionData(int redefinedCount) {
2424             this.redefinedCount = redefinedCount;
2425         }
2426 
2427         // initialize Unsafe machinery here, since we need to call Class.class instance method
2428         // and have to avoid calling it in the static initializer of the Class class...
2429         private static final Unsafe unsafe;
2430         // offset of Class.reflectionData instance field
2431         private static final long reflectionDataOffset;
2432 
2433         static {
2434             unsafe = Unsafe.getUnsafe();
2435             // bypass caches
2436             Field reflectionDataField = searchFields(Class.class.getDeclaredFields0(false),
2437                                                      "reflectionData");
2438             if (reflectionDataField == null) {
2439                 throw new Error("No reflectionData field found in java.lang.Class");
2440             }
2441             reflectionDataOffset = unsafe.objectFieldOffset(reflectionDataField);
2442         }
2443 
2444         static <T> boolean compareAndSwap(Class<?> clazz,
2445                                           SoftReference<ReflectionData<T>> oldData,
2446                                           SoftReference<ReflectionData<T>> newData) {
2447             return unsafe.compareAndSwapObject(clazz, reflectionDataOffset, oldData, newData);
2448         }
2449     }
2450 
2451     private volatile transient SoftReference<ReflectionData<T>> reflectionData;
2452 
2453     // Incremented by the VM on each call to JVM TI RedefineClasses()
2454     // that redefines this class or a superclass.
2455     private volatile transient int classRedefinedCount = 0;
2456 
2457     // Lazily create and cache ReflectionData
2458     private ReflectionData<T> reflectionData() {
2459         SoftReference<ReflectionData<T>> reflectionData = this.reflectionData;
2460         int classRedefinedCount = this.classRedefinedCount;
2461         ReflectionData<T> rd;
2462         if (useCaches &&
2463             reflectionData != null &&
2464             (rd = reflectionData.get()) != null &&
2465             rd.redefinedCount == classRedefinedCount) {
2466             return rd;
2467         }
2468         // else no SoftReference or cleared SoftReference or stale ReflectionData
2469         // -> create and replace new instance
2470         return newReflectionData(reflectionData, classRedefinedCount);
2471     }
2472 
2473     private ReflectionData<T> newReflectionData(SoftReference<ReflectionData<T>> oldReflectionData,
2474                                                 int classRedefinedCount) {
2475         if (!useCaches) return null;
2476 
2477         while (true) {
2478             ReflectionData<T> rd = new ReflectionData<>(classRedefinedCount);
2479             // try to CAS it...
2480             if (ReflectionData.compareAndSwap(this, oldReflectionData, new SoftReference<>(rd))) {
2481                 return rd;
2482             }
2483             // else retry
2484             oldReflectionData = this.reflectionData;
2485             classRedefinedCount = this.classRedefinedCount;
2486             if (oldReflectionData != null &&
2487                 (rd = oldReflectionData.get()) != null &&
2488                 rd.redefinedCount == classRedefinedCount) {
2489                 return rd;
2490             }
2491         }
2492     }
2493 
2494     // Generic signature handling
2495     private native String getGenericSignature0();
2496 
2497     // Generic info repository; lazily initialized
2498     private volatile transient ClassRepository genericInfo;
2499 
2500     // accessor for factory


2503         return CoreReflectionFactory.make(this, ClassScope.make(this));
2504     }
2505 
2506     // accessor for generic info repository;
2507     // generic info is lazily initialized
2508     private ClassRepository getGenericInfo() {
2509         ClassRepository genericInfo = this.genericInfo;
2510         if (genericInfo == null) {
2511             String signature = getGenericSignature0();
2512             if (signature == null) {
2513                 genericInfo = ClassRepository.NONE;
2514             } else {
2515                 genericInfo = ClassRepository.make(signature, getFactory());
2516             }
2517             this.genericInfo = genericInfo;
2518         }
2519         return (genericInfo != ClassRepository.NONE) ? genericInfo : null;
2520     }
2521 
2522     // Annotations handling
2523     private native byte[] getRawAnnotations();
2524     // Since 1.8
2525     native byte[] getRawTypeAnnotations();
2526     static byte[] getExecutableTypeAnnotationBytes(Executable ex) {
2527         return getReflectionFactory().getExecutableTypeAnnotationBytes(ex);
2528     }
2529 
2530     native ConstantPool getConstantPool();
2531 
2532     //
2533     //
2534     // java.lang.reflect.Field handling
2535     //
2536     //
2537 
2538     // Returns an array of "root" fields. These Field objects must NOT
2539     // be propagated to the outside world, but must instead be copied
2540     // via ReflectionFactory.copyField.
2541     private Field[] privateGetDeclaredFields(boolean publicOnly) {
2542         checkInitted();
2543         Field[] res;


3233         return (T) obj;
3234     }
3235 
3236     private String cannotCastMsg(Object obj) {
3237         return "Cannot cast " + obj.getClass().getName() + " to " + getName();
3238     }
3239 
3240     /**
3241      * Casts this {@code Class} object to represent a subclass of the class
3242      * represented by the specified class object.  Checks that the cast
3243      * is valid, and throws a {@code ClassCastException} if it is not.  If
3244      * this method succeeds, it always returns a reference to this class object.
3245      *
3246      * <p>This method is useful when a client needs to "narrow" the type of
3247      * a {@code Class} object to pass it to an API that restricts the
3248      * {@code Class} objects that it is willing to accept.  A cast would
3249      * generate a compile-time warning, as the correctness of the cast
3250      * could not be checked at runtime (because generic types are implemented
3251      * by erasure).
3252      *
3253      * @param <U> the type to cast this class object to
3254      * @param clazz the class of the type to cast this class object to
3255      * @return this {@code Class} object, cast to represent a subclass of
3256      *    the specified class object.
3257      * @throws ClassCastException if this {@code Class} object does not
3258      *    represent a subclass of the specified class (here "subclass" includes
3259      *    the class itself).
3260      * @since 1.5
3261      */
3262     @SuppressWarnings("unchecked")
3263     public <U> Class<? extends U> asSubclass(Class<U> clazz) {
3264         if (clazz.isAssignableFrom(this))
3265             return (Class<? extends U>) this;
3266         else
3267             throw new ClassCastException(this.toString());
3268     }
3269 
3270     /**
3271      * @throws NullPointerException {@inheritDoc}
3272      * @since 1.5
3273      */
3274     @SuppressWarnings("unchecked")


3363             return;
3364         declaredAnnotations = AnnotationParser.parseAnnotations(
3365             getRawAnnotations(), getConstantPool(), this);
3366         Class<?> superClass = getSuperclass();
3367         if (superClass == null) {
3368             annotations = declaredAnnotations;
3369         } else {
3370             annotations = new HashMap<>();
3371             superClass.initAnnotationsIfNecessary();
3372             for (Map.Entry<Class<? extends Annotation>, Annotation> e : superClass.annotations.entrySet()) {
3373                 Class<? extends Annotation> annotationClass = e.getKey();
3374                 if (AnnotationType.getInstance(annotationClass).isInherited())
3375                     annotations.put(annotationClass, e.getValue());
3376             }
3377             annotations.putAll(declaredAnnotations);
3378         }
3379     }
3380 
3381     // Annotation types cache their internal (AnnotationType) form
3382 
3383     private AnnotationType annotationType;

3384 
3385     void setAnnotationType(AnnotationType type) {
3386         annotationType = type;
3387     }
3388 
3389     AnnotationType getAnnotationType() {
3390         return annotationType;
3391     }
3392 
3393     /* Backing store of user-defined values pertaining to this class.
3394      * Maintained by the ClassValue class.
3395      */
3396     transient ClassValue.ClassValueMap classValueMap;
3397 
3398     /**
3399      * Returns an AnnotatedType object that represents the use of a type to specify
3400      * the superclass of the entity represented by this Class. (The <em>use</em> of type
3401      * Foo to specify the superclass in '... extends Foo' is distinct from the
3402      * <em>declaration</em> of type Foo.)
3403      *
3404      * If this Class represents a class type whose declaration does not explicitly
3405      * indicate an annotated superclass, the return value is null.
3406      *
3407      * If this Class represents either the Object class, an interface type, an
3408      * array type, a primitive type, or void, the return value is null.
3409      *
3410      * @return an object representing the superclass
3411      * @since 1.8
3412      */
3413     public AnnotatedType getAnnotatedSuperclass() {
3414          return TypeAnnotationParser.buildAnnotatedSuperclass(getRawTypeAnnotations(), getConstantPool(), this);
3415 }
3416 
3417     /**
3418      * Returns an array of AnnotatedType objects that represent the use of types to
3419      * specify superinterfaces of the entity represented by this Class. (The <em>use</em>
3420      * of type Foo to specify a superinterface in '... implements Foo' is
3421      * distinct from the <em>declaration</em> of type Foo.)
3422      *
3423      * If this Class represents a class, the return value is an array
3424      * containing objects representing the uses of interface types to specify
3425      * interfaces implemented by the class. The order of the objects in the
3426      * array corresponds to the order of the interface types used in the
3427      * 'implements' clause of the declaration of this Class.
3428      *
3429      * If this Class represents an interface, the return value is an array
3430      * containing objects representing the uses of interface types to specify
3431      * interfaces directly extended by the interface. The order of the objects in
3432      * the array corresponds to the order of the interface types used in the
3433      * 'extends' clause of the declaration of this Class.
3434      *
3435      * If this Class represents a class or interface whose declaration does not
3436      * explicitly indicate any annotated superinterfaces, the return value is an
3437      * array of length 0.
3438      *
3439      * If this Class represents either the Object class, an array type, a
3440      * primitive type, or void, the return value is an array of length 0.
3441      *
3442      * @return an array representing the superinterfaces
3443      * @since 1.8
3444      */
3445     public AnnotatedType[] getAnnotatedInterfaces() {
3446          return TypeAnnotationParser.buildAnnotatedInterfaces(getRawTypeAnnotations(), getConstantPool(), this);
3447     }
3448 }


2381             return name;
2382         }
2383         if (!name.startsWith("/")) {
2384             Class<?> c = this;
2385             while (c.isArray()) {
2386                 c = c.getComponentType();
2387             }
2388             String baseName = c.getName();
2389             int index = baseName.lastIndexOf('.');
2390             if (index != -1) {
2391                 name = baseName.substring(0, index).replace('.', '/')
2392                     +"/"+name;
2393             }
2394         } else {
2395             name = name.substring(1);
2396         }
2397         return name;
2398     }
2399 
2400     /**
2401      * Atomic operations support.
2402      */
2403     private static class Atomic {
2404         // initialize Unsafe machinery here, since we need to call Class.class instance method
2405         // and have to avoid calling it in the static initializer of the Class class...
2406         private static final Unsafe unsafe = Unsafe.getUnsafe();
2407         // offset of Class.reflectionData instance field
2408         private static final long reflectionDataOffset;
2409         // offset of Class.annotationType instance field
2410         private static final long annotationTypeOffset;
2411 
2412         static {
2413             Field[] fields = Class.class.getDeclaredFields0(false); // bypass caches
2414             reflectionDataOffset = objectFieldOffset(fields, "reflectionData");
2415             annotationTypeOffset = objectFieldOffset(fields, "annotationType");
2416         }
2417 
2418         private static long objectFieldOffset(Field[] fields, String fieldName) {
2419             Field field = searchFields(fields, fieldName);
2420             if (field == null) {
2421                 throw new Error("No " + fieldName + " field found in java.lang.Class");
2422             }
2423             return unsafe.objectFieldOffset(field);
2424         }
2425 
2426         static <T> boolean casReflectionData(Class<?> clazz,
2427                                              SoftReference<ReflectionData<T>> oldData,
2428                                              SoftReference<ReflectionData<T>> newData) {
2429             return unsafe.compareAndSwapObject(clazz, reflectionDataOffset, oldData, newData);
2430         }
2431 
2432         static <T> boolean casAnnotationType(Class<?> clazz,
2433                                              AnnotationType oldType,
2434                                              AnnotationType newType) {
2435             return unsafe.compareAndSwapObject(clazz, annotationTypeOffset, oldType, newType);
2436         }
2437     }
2438 
2439     /**
2440      * Reflection support.
2441      */
2442 
2443     // Caches for certain reflective results
2444     private static boolean useCaches = true;
2445 
2446     // reflection data that might get invalidated when JVM TI RedefineClasses() is called
2447     static class ReflectionData<T> {
2448         volatile Field[] declaredFields;
2449         volatile Field[] publicFields;
2450         volatile Method[] declaredMethods;
2451         volatile Method[] publicMethods;
2452         volatile Constructor<T>[] declaredConstructors;
2453         volatile Constructor<T>[] publicConstructors;
2454         // Intermediate results for getFields and getMethods
2455         volatile Field[] declaredPublicFields;
2456         volatile Method[] declaredPublicMethods;
2457         volatile Class<?>[] interfaces;
2458 
2459         // Value of classRedefinedCount when we created this ReflectionData instance
2460         final int redefinedCount;
2461 
2462         ReflectionData(int redefinedCount) {
2463             this.redefinedCount = redefinedCount;
2464         }























2465     }
2466 
2467     private volatile transient SoftReference<ReflectionData<T>> reflectionData;
2468 
2469     // Incremented by the VM on each call to JVM TI RedefineClasses()
2470     // that redefines this class or a superclass.
2471     private volatile transient int classRedefinedCount = 0;
2472 
2473     // Lazily create and cache ReflectionData
2474     private ReflectionData<T> reflectionData() {
2475         SoftReference<ReflectionData<T>> reflectionData = this.reflectionData;
2476         int classRedefinedCount = this.classRedefinedCount;
2477         ReflectionData<T> rd;
2478         if (useCaches &&
2479             reflectionData != null &&
2480             (rd = reflectionData.get()) != null &&
2481             rd.redefinedCount == classRedefinedCount) {
2482             return rd;
2483         }
2484         // else no SoftReference or cleared SoftReference or stale ReflectionData
2485         // -> create and replace new instance
2486         return newReflectionData(reflectionData, classRedefinedCount);
2487     }
2488 
2489     private ReflectionData<T> newReflectionData(SoftReference<ReflectionData<T>> oldReflectionData,
2490                                                 int classRedefinedCount) {
2491         if (!useCaches) return null;
2492 
2493         while (true) {
2494             ReflectionData<T> rd = new ReflectionData<>(classRedefinedCount);
2495             // try to CAS it...
2496             if (Atomic.casReflectionData(this, oldReflectionData, new SoftReference<>(rd))) {
2497                 return rd;
2498             }
2499             // else retry
2500             oldReflectionData = this.reflectionData;
2501             classRedefinedCount = this.classRedefinedCount;
2502             if (oldReflectionData != null &&
2503                 (rd = oldReflectionData.get()) != null &&
2504                 rd.redefinedCount == classRedefinedCount) {
2505                 return rd;
2506             }
2507         }
2508     }
2509 
2510     // Generic signature handling
2511     private native String getGenericSignature0();
2512 
2513     // Generic info repository; lazily initialized
2514     private volatile transient ClassRepository genericInfo;
2515 
2516     // accessor for factory


2519         return CoreReflectionFactory.make(this, ClassScope.make(this));
2520     }
2521 
2522     // accessor for generic info repository;
2523     // generic info is lazily initialized
2524     private ClassRepository getGenericInfo() {
2525         ClassRepository genericInfo = this.genericInfo;
2526         if (genericInfo == null) {
2527             String signature = getGenericSignature0();
2528             if (signature == null) {
2529                 genericInfo = ClassRepository.NONE;
2530             } else {
2531                 genericInfo = ClassRepository.make(signature, getFactory());
2532             }
2533             this.genericInfo = genericInfo;
2534         }
2535         return (genericInfo != ClassRepository.NONE) ? genericInfo : null;
2536     }
2537 
2538     // Annotations handling
2539     native byte[] getRawAnnotations();
2540     // Since 1.8
2541     native byte[] getRawTypeAnnotations();
2542     static byte[] getExecutableTypeAnnotationBytes(Executable ex) {
2543         return getReflectionFactory().getExecutableTypeAnnotationBytes(ex);
2544     }
2545 
2546     native ConstantPool getConstantPool();
2547 
2548     //
2549     //
2550     // java.lang.reflect.Field handling
2551     //
2552     //
2553 
2554     // Returns an array of "root" fields. These Field objects must NOT
2555     // be propagated to the outside world, but must instead be copied
2556     // via ReflectionFactory.copyField.
2557     private Field[] privateGetDeclaredFields(boolean publicOnly) {
2558         checkInitted();
2559         Field[] res;


3249         return (T) obj;
3250     }
3251 
3252     private String cannotCastMsg(Object obj) {
3253         return "Cannot cast " + obj.getClass().getName() + " to " + getName();
3254     }
3255 
3256     /**
3257      * Casts this {@code Class} object to represent a subclass of the class
3258      * represented by the specified class object.  Checks that the cast
3259      * is valid, and throws a {@code ClassCastException} if it is not.  If
3260      * this method succeeds, it always returns a reference to this class object.
3261      *
3262      * <p>This method is useful when a client needs to "narrow" the type of
3263      * a {@code Class} object to pass it to an API that restricts the
3264      * {@code Class} objects that it is willing to accept.  A cast would
3265      * generate a compile-time warning, as the correctness of the cast
3266      * could not be checked at runtime (because generic types are implemented
3267      * by erasure).
3268      *


3269      * @return this {@code Class} object, cast to represent a subclass of
3270      *    the specified class object.
3271      * @throws ClassCastException if this {@code Class} object does not
3272      *    represent a subclass of the specified class (here "subclass" includes
3273      *    the class itself).
3274      * @since 1.5
3275      */
3276     @SuppressWarnings("unchecked")
3277     public <U> Class<? extends U> asSubclass(Class<U> clazz) {
3278         if (clazz.isAssignableFrom(this))
3279             return (Class<? extends U>) this;
3280         else
3281             throw new ClassCastException(this.toString());
3282     }
3283 
3284     /**
3285      * @throws NullPointerException {@inheritDoc}
3286      * @since 1.5
3287      */
3288     @SuppressWarnings("unchecked")


3377             return;
3378         declaredAnnotations = AnnotationParser.parseAnnotations(
3379             getRawAnnotations(), getConstantPool(), this);
3380         Class<?> superClass = getSuperclass();
3381         if (superClass == null) {
3382             annotations = declaredAnnotations;
3383         } else {
3384             annotations = new HashMap<>();
3385             superClass.initAnnotationsIfNecessary();
3386             for (Map.Entry<Class<? extends Annotation>, Annotation> e : superClass.annotations.entrySet()) {
3387                 Class<? extends Annotation> annotationClass = e.getKey();
3388                 if (AnnotationType.getInstance(annotationClass).isInherited())
3389                     annotations.put(annotationClass, e.getValue());
3390             }
3391             annotations.putAll(declaredAnnotations);
3392         }
3393     }
3394 
3395     // Annotation types cache their internal (AnnotationType) form
3396 
3397     @SuppressWarnings("UnusedDeclaration")
3398     private volatile transient AnnotationType annotationType;
3399 
3400     boolean casAnnotationType(AnnotationType oldType, AnnotationType newType) {
3401         return Atomic.casAnnotationType(this, oldType, newType);
3402     }
3403 
3404     AnnotationType getAnnotationType() {
3405         return annotationType;
3406     }
3407 
3408     /* Backing store of user-defined values pertaining to this class.
3409      * Maintained by the ClassValue class.
3410      */
3411     transient ClassValue.ClassValueMap classValueMap;
3412 
3413     /**
3414      * Returns an AnnotatedType object that represents the use of a type to specify
3415      * the superclass of the entity represented by this Class. (The <em>use</em> of type
3416      * Foo to specify the superclass in '... extends Foo' is distinct from the
3417      * <em>declaration</em> of type Foo.)
3418      *
3419      * If this Class represents a class type whose declaration does not explicitly
3420      * indicate an annotated superclass, the return value is null.
3421      *
3422      * If this Class represents either the Object class, an interface type, an
3423      * array type, a primitive type, or void, the return value is null.
3424      *

3425      * @since 1.8
3426      */
3427     public AnnotatedType getAnnotatedSuperclass() {
3428          return TypeAnnotationParser.buildAnnotatedSuperclass(getRawTypeAnnotations(), getConstantPool(), this);
3429 }
3430 
3431     /**
3432      * Returns an array of AnnotatedType objects that represent the use of types to
3433      * specify superinterfaces of the entity represented by this Class. (The <em>use</em>
3434      * of type Foo to specify a superinterface in '... implements Foo' is
3435      * distinct from the <em>declaration</em> of type Foo.)
3436      *
3437      * If this Class represents a class, the return value is an array
3438      * containing objects representing the uses of interface types to specify
3439      * interfaces implemented by the class. The order of the objects in the
3440      * array corresponds to the order of the interface types used in the
3441      * 'implements' clause of the declaration of this Class.
3442      *
3443      * If this Class represents an interface, the return value is an array
3444      * containing objects representing the uses of interface types to specify
3445      * interfaces directly extended by the interface. The order of the objects in
3446      * the array corresponds to the order of the interface types used in the
3447      * 'extends' clause of the declaration of this Class.
3448      *
3449      * If this Class represents a class or interface whose declaration does not
3450      * explicitly indicate any annotated superinterfaces, the return value is an
3451      * array of length 0.
3452      *
3453      * If this Class represents either the Object class, an array type, a
3454      * primitive type, or void, the return value is an array of length 0.
3455      *

3456      * @since 1.8
3457      */
3458     public AnnotatedType[] getAnnotatedInterfaces() {
3459          return TypeAnnotationParser.buildAnnotatedInterfaces(getRawTypeAnnotations(), getConstantPool(), this);
3460     }
3461 }