加载类和实例化它之间的区别 [英] Difference between loading a class and instantiating it

查看:732
本文介绍了加载类和实例化它之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释类加载和实例化类之间的区别。当我们使用Static变量加载一个类时它是否也在Class加载的同时实例化?毕竟静态代码是类的一部分而不是它的个别实例。如果有人提供了一个例子来帮助我更好地理解这一点,将会很有帮助。

Could someone explain what is the difference between Class loading and instantiating a Class. When we load a class with Static variable does it also get instantiated the same time the Class get loaded? After all static code is part of the class rather than it's individual instances. It would be helpful if someone provided an example to help me understand this better.

推荐答案

这里有一些很好的解释(附带一个例子)和观察)

Here is some nice explanation(with an example and observation)

在JVM中加载并初始化类时--JP

当用Java加载类时


类加载由Java中的ClassLoaders完成,只要另一个类引用它或者延迟加载类直到需要进行类初始化,就可以实现加载类。如果Class在实际使用之前加载,它可以在初始化之前就位于内部。我相信这可能会有所不同,从JVM到JVM。虽然JLS保证在需要静态初始化时会加载一个类。

Class loading is done by ClassLoaders in Java which can be implemented to eagerly load a class as soon as another class references it or lazy load the class until a need of class initialization occurs. If Class is loaded before its actually being used it can sit inside before being initialized. I believe this may vary from JVM to JVM. While its guaranteed by JLS that a class will be loaded when there is a need of static initialization.

当一个类在Java中初始化时

When a Class is initialized in Java


当在Java
中初始化类时类加载后,会发生类的初始化,这意味着初始化类的所有静态成员。在以下情况下,用Java初始化类:

When a Class is initialized in Java After class loading, initialization of class takes place which means initializing all static members of class. A Class is initialized in Java when :

1)使用new()关键字创建类实例,使用类使用反射创建
。 forName(),它可能在Java中抛出
ClassNotFoundException。

2)调用Class的静态方法。

2) an static method of Class is invoked.

3)分配了
类的静态字段。

3) an static field of Class is assigned.

4)使用类的静态字段,它不是
常量变量。

4) an static field of class is used which is not a constant variable.

5)如果Class是顶级类,并且在类中嵌套嵌套的断言
语句被执行。

5) if Class is a top level class and an assert statement lexically nested within class is executed.

希望有帮助。

这篇关于加载类和实例化它之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆