java – 无法理解Class对象

有关内部锁和同步的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.

相关文章

摘要: 原创出处 https://www.bysocket.com 「公众号:泥瓦匠...
摘要: 原创出处 https://www.bysocket.com 「公众号:泥瓦匠...
今天犯了个错:“接口变动,伤筋动骨,除非你确定只有你一个...
Writer :BYSocket(泥沙砖瓦浆木匠)微 博:BYSocket豆 瓣:...
本文目录 线程与多线程 线程的运行与创建 线程的状态 1 线程...