简体   繁体   English

什么时候应该初始化类-在加载时或首次使用时?

[英]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() ):

  • Static initialization blocks might perform checks for external resources (eg files, database connection), and if those fail, you don't even want to continue the execution of your program. 静态初始化块可能会对外部资源(例如,文件,数据库连接)执行检查,如果这些失败,则您甚至不想继续执行程序。
  • Similar to the previous: loading external, native libraries. 与之前的相似:加载外部本机库。 If those fail (or not suitable for the current platform), you might want to detect that early and not continue with your app. 如果这些失败(或不适用于当前平台),则您可能希望及早发现该问题,而不继续使用您的应用程序。
  • Static initializaiton blocks might perform lengthy operations and you don't want to have delays/lags later on when they are really needed, you can initialize them early or on different, background threads. 静态初始化块可能会执行冗长的操作,并且您不希望稍后在真正需要它们时出现延迟/滞后,您可以提前或在不同的后台线程中对其进行初始化。
  • If you have static configuration files where class names are specified as text, you might want to initialize/load them early to detect configuration errors/typos. 如果您具有将类名指定为文本的静态配置文件,则可能需要及早初始化/加载它们以检测配置错误/错别字。 Such examples are logger config files, web.xml, spring context etc. 这样的示例是记录器配置文件,web.xml,spring上下文等。
  • Many classes in the standard Java library cache certain data like the HTTPUrlConnection caches the HTTP user agent returned by System.getProperty("http.agent") . 标准Java库中的许多类都缓存某些数据,例如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: 您不应该提早初始化的情况:

  • Classes which might only need in rare cases, or they might not even be needed at all throughout the run of your application. 仅在极少数情况下可能需要的类,或者甚至可能在整个应用程序运行过程中根本不需要这些类。 For example a GUI application might only show the About dialog when the user selects the Help/About menu. 例如,当用户选择“帮助/关于”菜单时,GUI应用程序可能仅显示“关于”对话框。 Obviously no need to load the relevant classes early (eg 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.

相关问题 首次尝试使用多个类时出现NullPointerException错误 - Getting NullPointerException errors when trying to use multiple classes for the first time 第一次显示时仅加载一次标签(片段),并将其保留以备后用 - Load tab (Fragment) only once when it is shown for the first time and retain it for later use 什么时候是在Java中使用泛型类的正确时间 - When is the right time to use generic classes in Java 在使用加载时间编织时未编织的超级类中的@Transactional - @Transactional in super classes not weaved when using load time weaving 在运行时加载JAR文件类时出错 - Error when load JAR file classes at run time 如何定义第一次调用我的 @Scheduled 方法的时间? - How to define when my @Scheduled method should be called first time? 我应该将 Java 日期和时间类或 go 与 Joda Time 这样的第三方库一起使用吗? - Should I use Java date and time classes or go with a 3rd party library like Joda Time? 在实现if else进行比较时,我应该首先使用!=或== - Should I use != or == first when implementing an if else for comparison 首次加载页面时,Webdriver需要很长时间才能找到第一个元素 - When the page load for the first time , webdriver takes a long time to find the first element JMXBean何时初始化 - When is JMXBean initialised
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM