簡體   English   中英

調用時如何使靜態屬性評估

[英]How can I make Static Property evalute when called

Java是否在類中內聯聲明時僅調用一次聲明的變量? 每當我調用它時如何使它更新?

https://ideone.com/3WUWyO

public class MyClass {

    private static int level = 0;

    private boolean levelInline = (10 <= level);
    private boolean levelFunction = less(10,level);


    public static void main(String args[]) {

        level = 10;


       if (levelInline) {
           System.out.println("Inline True");
       }

       if (levelFunction) {
           System.out.println("Function True");
       }


        levelInline = (10 <= level);

        if (levelInline) {
            System.out.println("InLine True");
        }

        if (levelFunction) {
           System.out.println("Function True");
       }


    }

    private static boolean less(int a, int b) {
        return (a <= b);
    }


}

我希望每次查詢levelInLinelevelFunction ,都會再次評估相關的正確表達式。 即我預期的結果是:

Inline True
Function True
Inline True
Function True

我要做什么,而不是這樣:

 int debugLevel = 0;
 int levelToDoX = 5;
 int levelToDoY = 8;
 int levelToDoZ = 10;
 boolean DoX = debugLevel >= levelToDoX;
 boolean DoY = debugLevel >= levelToDoY;
 boolean DoZ = debugLevel >= levelToDoZ;

有這個:

 int debugLevel = 0;
 boolean DoX = debugLevel >= 5;
 boolean DoY = debugLevel >= 8;
 boolean DoZ = debugLevel >= 10;

我試圖跳過必須在其自己的變量中保留魔術數字的步驟-雖然直接將數字與布爾值合並會更有意義,但這樣會使其更整潔和易於維護。

但這不是Java變量的工作方式。 為變量(或成員)分配值后,它就只是一個值。 它沒有關於該值的計算方式的“內存”,並且在您訪問它時不會重新計算它。 如果要重新計算該值,則應定義一個方法:

private static boolean levelFunction() {
    return less(10, level);
}

並在需要時調用它:

if (levelFunction()) {
    System.out.println("Function True");
}

您可以使用“功能接口”和lambda來近似所需

public static Function<Integer,Boolean> levelInline = (Integer level) -> 10 <= level;

public static void main(String[] args) throws Exception
{
    int level = 5;
    System.out.println(levelInline.apply(level));

    level = 10;
    System.out.println(levelInline.apply(level));

}

這聲明了一個匿名類型,該類型實現了一個帶有Integer參數並返回BooleanFunction ,該Boolean實現為lambda。 然后,您可以在需要時通過調用它的apply()方法來執行它。

在Oracle Java教程中閱讀“功能接口”和“ lambda”。

正如@Aominè所建議的(謝謝)

public static IntPredicate levelInline = (int level) -> 10 <= level;
...
int level = 5;
System.out.println(levelInline.test(level));

java中的static在類級別,這意味着它們在加載類時得到評估。

在您的情況下,當類加載時,level設置為0,levelInLine = false,levelFunction為false。 這些值將保持不變,直到您對其進行更改。

然后運行main()方法,由於上述原因,將跳過前兩個if語句。

然后您再次更改levelInLine,這一次它將設置為true。

因此,第38行中的下一個if語句將導致打印輸出。 但是下一個if語句將不會輸出,因為此時levelFunction仍為false。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM