加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 无法理解Class对象

发布时间:2020-12-15 00:53:56 所属栏目:Java 来源:网络整理
导读:有关内部锁和同步的Oracle Java文档说: You might wonder what happens when a static synchronized method is invoked,since a static method is associated with a class,not an object. In this case,the thread acquires the intrinsic lock for the Cl
有关内部锁和同步的Oracle Java文档说:

You might wonder what happens when a static synchronized method is
invoked,since a static method is associated with a class,not an
object. In this case,the thread acquires the intrinsic lock for the
Class object associated with the class. Thus access to class’s static
fields is controlled by a lock that’s distinct from the lock for any
instance of the class.

我没有完全理解Class对象的概念.在了解了一些在线内容之后,我了解到:

A Class object is sort of a meta object describing the class of an object such as name,package etc.

我的问题是:

>什么时候创建?
>在某些时间收集垃圾吗?
>由于它是由synchronized static方法使用的,它是否意味着每个JVM只有一个Class对象的实例?

有一个类似的问题what is Class Object(java.lang.class) in java.但它没有回答我的问题.

[更新]

在manouti提供的答案的评论部分中添加了一个新问题,因为他提到可以有多个Class对象实例:

>如果存在多个Class对象实例,是否有可能同时由多个线程访问静态同步方法?

解决方法

1.什么时候创建?

它是在JVM使用类加载器加载类时创建的.当某个类被其他类引用时,将加载该类. ClassLoader通常在调用ClassLoader#loadClass(String className)时创建此Class实例.这将在this link from the Java Language Specification中解释:

Loading refers to the process of finding the binary form of a class or interface type with a particular name,perhaps by computing it on the fly,but more typically by retrieving a binary representation previously computed from source code by a Java compiler,and constructing,from that binary form,a Class object to represent the class or interface.

2.在某些时间收集垃圾吗?

与任何其他实例一样,如果Class实例不再可访问,则它符合GC的条件.当没有可以访问Class实例所表示的类型的对象时,就会发生这种情况,并且加载该类的类加载器也不可访问.

3.由于它是由synchronized static方法使用的,它是否意味着每个JVM只有一个Class对象实例?

不必要.如果您定义了一个自定义类加载器,那么您可以拥有一个Class的两个实例.在这种情况下,如果您尝试将某个类A的对象转换为“相同类型”A(如果它们由两个不同的类加载器加载),您甚至可能会获得ClassCastException.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读