如何检查一个类是否被初始化? [英] How to check whether a class is initialized?

查看:585
本文介绍了如何检查一个类是否被初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您可能会问,我为什么要这样做-这是因为我正在使用一个类(来自外部库),该类在其静态初始化程序中进行填充,因此我需要知道它是否已完成.

You'll probably ask, why would I want to do that - it's because I'm using a class (from an external library) which does stuff in its static initializer and I need to know whether it's been done or not.

我查看了ClassLoader,但没有发现任何有用的内容.有什么想法吗?

I looked at ClassLoader, but didn't find anything that looked useful. Any ideas?

推荐答案

您可以使用ClassLoader.findLoadedClass()方法.如果返回null,则不会加载该类.这样,如果尚未加载该类,则不会加载它.

You can use the ClassLoader.findLoadedClass() method. If it returns null, then the class isn't loaded. This way you don't load the class if it wasn't already loaded.

警告:此代码在这里实际上不起作用,在系统ClassLoader中,findLoadedClass()受保护,您需要使用自己的ClassLoader覆盖它.

WARNING : This code doesn't really work here, in the system ClassLoader, findLoadedClass() is protected, you need to override it with your own ClassLoader.

检查下面的链接关于同一主题,以检查是否使用系统ClassLoader加载了一个类

Check the link below On the same topic to check if a class is loaded with the system ClassLoader

if(ClassLoader.getSystemClassLoader().findLoadedClass("java.lang.String") != null){
    System.out.println("Yepee, String is loaded !");
}


@irreputable的一个很好的观点:


Very good point from @irreputable :

已加载"并不意味着已初始化".初始化仅在JLS3 $ 12.4.1定义的精确时刻发生

"loaded" doesn't mean "initialized". initialization only happens at precise moments defined by JLS3 $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 声明的静态字段,并且该字段不是常量变量
  • 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.

在类Class中和在包java.lang.reflect中的某些反射方法的调用也会导致类或接口的初始化.在任何其他情况下,都不会初始化类或接口.

Invocation of certain reflective methods in class Class and in package java.lang.reflect also causes class or interface initialization. A class or interface will not be initialized under any other circumstance.


资源:

  • Javadoc - ClassLoader.findLoadedClass()
  • Internals of Java Class Loading
  • JLS - §12.4.1 When Initialization Occurs

关于同一主题:

这篇关于如何检查一个类是否被初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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