Java类加载器是否保证不加载未使用的类? [英] Is Java class loader guaranteed to not load classes that aren't used?

查看:461
本文介绍了Java类加载器是否保证不加载未使用的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否保证(默认的系统)Java类加载器尝试加载正在运行的代码中未引用的类?我的意思的几个例子:

Is there a guarantee that (the default, system) Java class loader doesn't attempt to load classes that aren't referred to in the code being run? A couple of examples of what I mean:


  • 我正在使用 framework.jar 我知道其中包含对另一个 library.jar 的类的引用,但我只使用了不包含这些引用的框架的这一部分。保留 library.jar out是否安全?

  • 首次加载类时会运行静态块。如果没有正在运行的代码包含对特定类的引用,是否确定它的静态块没有运行?

  • I'm using a framework.jar which I know to contain references to another library.jar's classes in it, but I'm using only such part of the framework that doesn't contain those references. Is it safe to leave library.jar out?
  • Static blocks are run when a class is first loaded. If no running code contains references to a specific class, is it sure that it's static block is not run?

快速测试它似乎按照上面的假设工作,无论如何加载未使用的类都没有多大意义,但是否有保证

Quickly testing it seems to work as assumed above, and it wouldn't make much sense to load unused classes anyway, but is there any guarantee on this?

添加:似乎我的静态块在第一次加载类时运行上面的语句有些不正确。在没有运行它们的情况下,加载类(一件事)绝对是可能的(另一件事)。所以我对这两种情况都感兴趣;保证类没有加载,而不是运行

Addition: It seems that my "static blocks are run when a class is first loaded" statement above is somewhat incorrect. It's definitely possible to load classes (one thing) without running them (another thing). So I'm interested in both cases; guarantees about classes not getting loaded, and not getting run.

推荐答案

没有这样的保证 1 wrt加载类。

There is no such guarantee1 wrt the loading of the classes.

但是,保证静态块不会过早运行。触发类初始化的事件在 JLS中指定12.4.1

However, you are guaranteed that static blocks won't be run prematurely. The events that trigger class initialization are specified in JLS 12.4.1.


类或接口类型T将在第一次出现以下任何一个之前立即初始化:

A class or interface type T will be initialized immediately before the first occurrence of any one of the following:


  • T是一个类,创建了一个T实例。

  • T是一个类并且调用由T声明的静态方法。

  • 分配由T声明的静态字段。

  • 使用由T声明的静态字段,该字段不是常量变量(§4.12.4)。

  • T是顶级类,并且执行词法嵌套在T中的断言语句(§14.10)。

  • T is a class and an instance of T is created.
  • T is a class and a static method declared by T is invoked.
  • A static field declared by T is assigned.
  • A static field declared by T is used and the field is not a constant variable (§4.12.4).
  • T is a top-level class, and an assert statement (§14.10) lexically nested within T is executed.






1 - 观察到当前一代Java实现不会不必要地加载类,但这不是保证。唯一的保证是它在官方规范中写的。

这篇关于Java类加载器是否保证不加载未使用的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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