gpt4 book ai didi

java - 如何知道Java类是否已初始化

转载 作者:行者123 更新时间:2023-12-01 16:02:29 26 4
gpt4 key购买 nike

如何知道一个类是否已经初始化?

Class cl = Class.forName("com.example.MyClass", false, getClass().getClassLoader());
// the false argument above indicates that the class should not be initialized
// but how can I check whether it already was?
cl.isInitialized(); // this does not exist, how can I know instead?

关于我为什么想知道:

在客户的项目中,我们有一个丑陋的类(*),其中有很多我想测试的静态成员。为了使测试可预测,静态成员必须具有在初始化时设置的默认值。如果 JUnit 测试为每个测试类启动一个新的 JVM,那么这不是问题:每次执行时都会重新加载该类。但是,当我与其他人一起在 Eclipse 中执行测试时,相同的 JVM 用于多个测试,并且该类不是新加载的,并且成员不再具有默认值。我希望能够决定测试是否有意义(因为类将被重新加载),或者我是否应该返回,因为如果静态成员已被修改,测试就没有意义。

(*) 重构已安排,但不只是现在

该类的简化版本

public class Settings {
public static Properties props;
static{
props.setProperty("key1", "val1");
props.setProperty("key2", "val2");
}
}

以及测试类

public class SettingsTest extends TestCase {
public void testDefauts() throws Exception {
Class cl = Class.forName("Settings", false, getClass().getClassLoader());
if(cl.isInitialized){ // doesn't exist
// Cannot test default values, because class was already initialized
return;
}

Properties props = Settings.props; // Settings is initialized here
assertEquals("val1", props.getProperty("key1"));
assertEquals("val2", props.getProperty("key2"));
}
}

最佳答案

类的静态初始值设定项(即 static { ... } block 的调用方式)在类加载器第一次加载类时执行。它们保证仅被调用一次,并且在允许任何其他线程访问该类之前以线程安全的方式调用。

我不确定您的单元测试有多大值(value)。您正在测试由 static {...} block 放入 Properties 对象中的值。仅根据 Settings 类本身中的代码就可以直接查看默认/初始值是什么?换句话说,您正在测试不会失败的逻辑,除非有人更改默认值。

我认为你最好只删除静态 block 、静态属性对象(听起来像)其他线程/类正在修改的内容等;而不是花费大量时间试图找到一种体面的方法来对丑陋的代码进行单元测试。

关于java - 如何知道Java类是否已初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3466538/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com