[英]When should classes be initialised - at load time or at first use?
One can load a class dynamically using this method of java.lang.Class
: 可以使用此
java.lang.Class
方法动态加载类:
public static Class<?> forName(String name, boolean initialize,
ClassLoader loader)
According to the JavaDoc , the second parameter is used to control the timing of class initialization (execution of static initialization code). 根据JavaDoc ,第二个参数用于控制类初始化(执行静态初始化代码)的时间。 If
true
, the class is initialized after loading and during the execution of this method; 如果为
true
,则在加载后和执行此方法期间初始化该类;否则,将初始化该类。 if false
, initialization is delayed until the first time the class is used. 如果为
false
,则初始化将延迟到第一次使用该类之前。
Now, I understand all that, but the docs don't say how to decide which strategy to use. 现在,我了解了所有内容,但是文档没有说明如何决定使用哪种策略。 Is it better to always do initialization immediately?
总是立即进行初始化更好吗? Is it better to always delay it to first use?
总是延迟首次使用会更好吗? Does it depend on the circumstances?
是否取决于情况?
Yes, it depends on circumstances, but usually it is preferred to just let classes be loaded and initialized on first use. 是的,这取决于具体情况,但是通常最好仅在第一次使用时让类被加载和初始化。
Cases when you might want to early initialize them (eg by calling forName()
for them): 您可能想及早初始化它们的情况(例如,通过为它们调用
forName()
):
HTTPUrlConnection
caches the HTTP user agent returned by System.getProperty("http.agent")
. HTTPUrlConnection
缓存System.getProperty("http.agent")
返回的HTTP用户代理。 When it is first used, its value will be cached and if you change it (with like System.setProperty()
), the new value will not be used. System.setProperty()
),将不使用新值。 You can force such caching if you initialize the proper classes early, protecting them to be modified by the code later on. Cases when you should not initialize early: 您不应该提早初始化的情况:
AboutDialog
) because this is a rare case and in most runs the user will not do this / need this. AboutDialog
),因为这种情况很少见,并且在大多数运行中,用户将不需要/不需要这样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.