簡體   English   中英

內部類中訪問的變量

[英]variable accessed within inner class

我有以下代碼可用於執行根命令:

public static String sudo(final String cmd, Context ctx) {
    String output = null;  //init string output
    if (RootTools.isRootAvailable()) {
        if (RootTools.isAccessGiven()) {
            try {
                CommandCapture command = new CommandCapture(0, cmd) {
                    @Override
                    public void output(int id, String line) {
                        Log.d("com.vwade79.aokpdelta.Functions.sudo", "cmd:"+cmd+"\noutput:"+line);
                        if (line.equals("")) {
                            return;
                        }
                        else {
                            output = line;  //ERROR
                        }
                    }
                };
                RootTools.getShell(true).add(command).waitForFinish();
            } catch (Exception e) {
                Toast.makeText(ctx, "There was an error executing root command : "+cmd, Toast.LENGTH_LONG).show();
                e.printStackTrace();
            }
        }
        else {
            Toast.makeText(ctx, "Root permission isn't given!", Toast.LENGTH_LONG).show();
            Intent intent = new Intent(ctx, MainActivity.class);
            ctx.startActivity(intent);
        }
    }
    else {
        Toast.makeText(ctx, "You're not rooted! Come back when you are!", Toast.LENGTH_LONG).show();
        Intent intent = new Intent(ctx, MainActivity.class);
        ctx.startActivity(intent);
    }
    return output;
}

我收到一個錯誤:

variable "output" is accessed from within inner class. Needs to be declared final.

我不知道如何分配“內部類”的輸出。

錯誤消息說明了一切:您只能從內部類中訪問final變量。

一個快速的解決方案是定義:

final String output[] = new String[1];  //init string output

在內部類中:

                        output[0] = line;  // No ERROR :-)

接着:

return output[0];

這是因為數組本身是final,但是數組的內容仍可以更改(如果您問我,Java中final定義有點奇怪; final並不意味着不變)。

暫無
暫無

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

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