局部变量必须是最终的或有效的最终 [英] local variables must be final or effectively final
问题描述
我在Java 8中有一个异步操作,它返回一个onError回调或onSuccess回调。如果操作成功与否,我需要返回我的方法。所以我返回一个布尔值来说明这个信息。我遇到的问题是我得到以下编译错误:
I have an async operation inside of Java 8 which return an onError callback or an onSuccess callback. I need to return inside of my method if the operation was a success or not. So I am returning a boolean to state this information. The problem I am facing is I get the following compilation error:
错误:从内部类引用的局部变量必须是final或
有效最终
error: local variables referenced from an inner class must be final or effectively final
搜索错误我可以看到你不允许这种类型的操作,但是如果操作是否成功?
Googling the error I can see you this type of operation is not allowed, but then how can I return if the operation was a success or not?
public Boolean addUser(String email, String password) {
Boolean isSuccess = false;
Map<String, AttributeValue> item = new HashMap<String, AttributeValue>();
item.put("email", new AttributeValue(email)); //email
item.put("password", new AttributeValue(password)); //password
dynamoDB.putItemAsync(new PutItemRequest().withTableName("Users").withItem(item), new AsyncHandler() {
@Override
public void onError(Exception excptn) {
}
@Override
public void onSuccess(AmazonWebServiceRequest rqst, Object result) {
isSuccess = true;
}
});
return isSuccess;
}
推荐答案
这是不是一个好的做法,也可能不起作用。在您的代码中,新的AsyncHandler()
将在一个单独的线程中运行。由于它不是阻塞调用,因此主线程不会等待它完成。
This is not a good practice and also, it might not work. In your code, new AsyncHandler()
will be running in a separate thread. Since it's not a blocking call, main thread will not wait for it's completion.
所以,在调用 dynamoDB.putItemAsync(...)
之后会发生什么,返回语句甚至在您的 AsyncHandler()
完成它的执行并更改 isSuccess
的值之前,它将被执行。这意味着, return isSuccess;
可能会返回默认值 false
。
So, what will happen is, just after calling dynamoDB.putItemAsync(...)
, the return statement will get executed even before your AsyncHandler()
finishes it's execution and changes the value of isSuccess
. That means, return isSuccess;
might return the default value false
.
注意:如果您真的想这样做,可以将布尔变量设为 field 变量。
Note: If you really want to do it this way, you can make the boolean variable as a field variable.
public boolean isSuccess = false;
这篇关于局部变量必须是最终的或有效的最终的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!