gpt4 book ai didi

java - 如何在 JAVA 类中构建以下需求

转载 作者:行者123 更新时间:2023-11-30 09:18:12 24 4
gpt4 key购买 nike

场景是这样的:

  1. 数据库“overAllCount”中有一个字段包含一些值。
  2. 我必须在我设计的许多类中使用这个变量。
  3. 我想在一个类中获取这个“overAllCount”,比如“OverAllCountClass”,并在所有子类中使用它,其类名如 OverAllCountClass.overAllCount。基本上就像一个静态变量。

我该怎么做?
我的解决方案是:

public Class OverAllCountClass {

public static int OverAllCount;

public OverAllCountClass(){

// Fetch overAllCount from database here and set its value

}
}

//////////像这样使用//////////////

 public class Usecount {

public void abc(){

// BUT IT IS NOT POSSIBLE becuase OverAllCountClass is not yet initialize
int mycount = OverAllCountClass.overAllCount

}
}

我怎样才能做到这一点?

最佳答案

如果您担心静态变量 overAllCount 可能不会被初始化,并且如果您希望它在类 OverAllCountClass 首次被调用时被初始化,那么您可以使用 Static initializer blocks

public class OverAllCountClass {

public static int overAllCount;

static {
overAllCount = fetchOverAllCount();
}
}

静态初始化程序 block 第一次加载类时调用。当 JVM 发现一个类被使用时,它首先加载一个类。

public class Usecount {

public void abc(){
//When JVM sees that OberAllCountClass is used here, it executes the static block of OverAllCountClass and by the time below statement is executed, overAllCount is initialized
int mycount = OverAllCountClass.overAllCount
}
}

关于java - 如何在 JAVA 类中构建以下需求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18586150/

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