簡體   English   中英

如何從main方法(或任何方法)中的args []初始化java中的常量,例如“ public static final Integer”

[英]How to initialize constant such as “public static final Integer” in java from args[] in main method (or any)

我基本上是Java的初學者,並且我試圖找出這個問題:

我的項目通過許多類使用(整數)常量,我需要從programm的文件/參數中設置此常量,但我不知道如何。 我可以刪除“ final”語句,但這違反所有約定。

如何解決呢? 避免這種情況的最佳方法是什么? 請幫我 :)

簡短的例子:

public class App {
    public static final int k;  
    public static void main( String[] args ) {
        k = Integer.parseInt(args[0]); // does not work ... sure but how? 
    }
}

編輯:公共靜態無效主...(它缺少靜態)

您只能在static { }塊中使用這種功能。

我建議將常量本身設為私有,並且只能通過public static getter方法訪問。 這應該是一個合適的體系結構。

您需要使用static{}塊:

public class App {
    public static final int k;

    static {
        String kvalue = "";
        try
        {
            // Insert some code to open a file and read a value from it.
            kvalue = "<value from file>";
        }
        catch( Exception e )
        {
            // handle any exceptions opening the file
        }
        finally
        {
            k = Integer.parseInt( kvalue );
        }
    }

    public static void main( final String[] args ) {
        // do stuff
    }
}

或者,您可以讓每個需要此值訪問共享數據池ApplicationContext ,其中值X將作為常量駐留在其中:

public final class ApplicationContext {

    public static abstract class Worker {

        private final ApplicationContext mApplicationContext;

        public Worker(final ApplicationContext pApplicationContext) {
            this.mApplicationContext = pApplicationContext;
        }


        public final ApplicationContext getApplicationContext() {
            return this.mApplicationContext;
        }

    }

    private final int mX;

    ApplicationContext(final String[] pArgs) {
        this.mX = pArgs[0];
    }


    public final int getX() {
        return this.mX();
    }

}

通過使所有相關的類擴展ApplicationContext.Worker ,我們可以確保訪問常量值而不必依賴static實現,因為所有類在構造時都會收到對ApplicationContext的引用。

它不起作用,因為static final變量只能在靜態塊中初始化。

暫無
暫無

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

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