簡體   English   中英

無法訪問java中的內部類問題

[英]Unable to access Inner class issue in java

從內部類引用的局部變量必須是最終的或有效的最終錯誤顯示在下面的代碼中:

public Vector<Map<String, Object>> newsFeedConnection(String var, Hashtable punishment) {
    ConnectionRequest connectionRequest;
    connectionRequest = new ConnectionRequest() {
        @Override
        protected void readResponse(InputStream input) throws IOException {
            JSONParser p = new JSONParser();
            results = p.parse(new InputStreamReader(input));

            punishment = (Hashtable) results.get("punishment");
        }
    }
}

但是當我將其更改為final(下面的代碼)時,它會再次給出“無法為最終變量懲罰賦值”錯誤。

public Vector<Map<String, Object>> newsFeedConnection(String var, final Hashtable punishment) {
    ConnectionRequest connectionRequest;
    connectionRequest = new ConnectionRequest() {
        @Override
        protected void readResponse(InputStream input) throws IOException {
            JSONParser p = new JSONParser();
            results = p.parse(new InputStreamReader(input));

            punishment = (Hashtable) results.get("punishment");
        }
    }
}

我該如何解決這個問題?如果我設置了一個全局變量,我就無法從其他類中的方法中訪問該值。

您正在重新創建一個概念上不可接受的最終變量,只需更改懲罰中的值而不再創建它,這將解決您的問題。

傳遞值與傳遞參考 - 傳遞對象引用時,您正在通過引用傳遞。 執行此操作時,可以通過在對象上調用適當的方法來更改對象的狀態,但不能更改對象本身的引用。 例如:

    public class TestPassByReference {

    public static void main(String[] args){
        StringBuilder stringBuilder = new StringBuilder("Lets Test!");
        changeStringDoesNotWork(stringBuilder);
        System.out.println(stringBuilder.toString());
        changeString(stringBuilder);
        System.out.println(stringBuilder.toString());
    }

    static void changeString(StringBuilder stringBuilder){
        stringBuilder.append(" Yeah I did it!");
    }

    static void changeStringDoesNotWork(StringBuilder stringBuilder){
        stringBuilder = new StringBuilder("This will not work!");
    }
}

輸出:

Lets Test!               //Value did not change
Lets Test! Yeah I did it!

我希望你現在可以將你想要做的事情與這個基本方面聯系在一起,因而不正確。

你可以做的是:

HashTable tempHashTable = (Hashtable) results.get("punishment");    
punishment.clear();
punishment.putAll(tempHashTable);

另外為什么要使用HashTable? 有更好的線程安全集合類,可以提供更好的性能。

您可以通過更新punishment變量來解決它:

public Vector<Map<String, Object>> newsFeedConnection(String var,  final Hashtable punishment) {
        ConnectionRequest connectionRequest;
        connectionRequest = new ConnectionRequest() {
            @Override
            protected void readResponse(InputStream input) throws IOException {
                JSONParser p = new JSONParser();
                results = p.parse(new InputStreamReader(input));

                punishment.putAll((Hashtable) results.get("punishment"));
                  }
            }
        }
}

暫無
暫無

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

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