Java:使用局部变量的匿名内部类 [英] Java: Anonymous inner class using a local variable

查看:85
本文介绍了Java:使用局部变量的匿名内部类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在我的匿名内部子类中获取传递给此方法的 userId 的值?

How can I get the value of userId passed to this method in my anonymous inner subclass here?

public void doStuff(String userID) {
    doOtherStuff(userID, new SuccessDelegate() {
        @Override
        public void onSuccess() {
            Log.e(TAG, "Called delegate!!!! "+ userID);
        }
    });
}

我收到此错误:

不能在不同方法中定义的内部类中引用非最终变量 userID

Cannot refer to a non-final variable userID inside an inner class defined in a different method

我很确定我不能将它分配为 final,因为它是一个具有未知值的变量.我听说这种语法确实以某种方式保留了作用域,所以我认为一定有一个我还不太了解的语法技巧.

I'm pretty sure I can't assign it as final since it's a variable with an unknown value. I had heard that this syntax does preserve scope in some way, so I think there must be a syntax trick I don't quite know yet.

推荐答案

当然可以将其指定为 final - 只需将该关键字放在参数的声明中即可:

Sure you can assign it as final - just put that keyword in the declaration of the parameter:

public void doStuff(final String userID) {
   ...

我不知道你说它是一个未知值的变量是什么意思;最后的意思是,一旦一个值被赋值给变量,它就不能被重新赋值.由于您没有在方法中更改 userID 的值,因此在这种情况下将其设为 final 没有问题.

I'm not sure what you meant about it being a variable with an unknown value; all that final means is that once a value is assigned to the variable, it cannot be re-assigned. Since you're not changing the value of the userID within your method, there's no problem making it final in this case.

这篇关于Java:使用局部变量的匿名内部类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆