【问题标题】:variable accessed within inner class在内部类中访问的变量
【发布时间】:2013-08-31 05:25:49
【问题描述】:

我有以下代码可用于执行根命令:

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.

我不知道如何分配“内部类”的输出。

【问题讨论】:

    标签: java android class variables


    【解决方案1】:

    错误消息说明了一切:您只能从内部类中访问 final 变量。

    一个快速的解决方案是定义:

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

    在内部类中:

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

    然后:

    return output[0];
    

    这是因为数组本身是final的,但是数组的内容还是可以改变的(Java中final的定义有点奇怪,如果你问我;final并不意味着不可变)。

    【讨论】:

    • 哦,谢谢,我想到了这一点,但认为决赛会让它变得不可变哈哈。
    猜你喜欢
    • 2013-07-08
    • 2011-08-04
    • 2018-03-04
    • 2015-05-25
    • 1970-01-01
    • 2011-06-15
    • 2021-11-05
    • 1970-01-01
    相关资源
    最近更新 更多