2 回答

TA貢獻1770條經(jīng)驗 獲得超3個贊
package myapp;
import java.util.concurrent.TimeUnit;
import java.lang.InterruptedException;
public class ExampleClass {
public static int usefulValue;
public ExampleClass(){
ExampleClass.usefulValue = slowMethod();
}
private int slowMethod(){ //just an example of something that takes time
int usefulValue;
try {
TimeUnit.SECONDS.sleep(500);
} catch (InterruptedException e){
;
}
usefulValue = 15;
return usefulValue;
}
public int getUsefulValue(){
return ExampleClass.usefulValue;
}
}
同樣在任何其他類中,您可以像這樣使用它的值,ExampleClass.usefulValue因此它的值在整個應(yīng)用程序中或在此線程中保持不變。

TA貢獻1869條經(jīng)驗 獲得超4個贊
您可以使用延遲初始化。
private Integer usefulValue;
public ExampleClass(){
// this.usefulValue = slowMethod();
}
public int getUsefulValue(){
if (this.usefulValue == null) {
this.usefulValue = slowMethod();
}
return this.usefulValue;
}
或用于此:lombok
添加回答
舉報