作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
场景是这样的:
我该怎么做?
我的解决方案是:
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/
我是一名优秀的程序员,十分优秀!