[英]The final local variable dc cannot be assigned, since it is defined in an enclosing type
public static void createTable() {
final DatabaseConnection dc;
final Connection con;
final String que;
Statement state;
new Thread(() -> {
dc = new DatabaseConnection("check_table_exists");
con = dc.con;
que = "CREATE TABLE IF NOT EXISTS " + DatabaseConnection.TABLE + " (id INT(11) NOT NULL AUTO_INCREMENT,itemId INT(200), itemName VARCHAR(200), amount INT(200),uuid VARCHAR(200), timestamp BIGINT(200), PRIMARY KEY (id))";
try {
state = con.createStatement();
state.execute(que);
state.close();
dc.close();
}
catch (SQLException e) {
e.printStackTrace();
dc.close();
}
}).start();
}
I was just wondering as to how I can solve this problem.我只是想知道如何解决这个问题。 I am also receiving an error 'Local variable state defined in an enclosing scope must be final or effectively final' on the 'state' variable.我还在“状态”变量上收到错误“在封闭 scope 中定义的局部变量 state 必须是最终或有效最终”。 I believe this is because I am using some old source code I found, however, I cannot seem to find the solution.我相信这是因为我使用了一些我找到的旧源代码,但是,我似乎找不到解决方案。
With Java, you cannot assign anything to a variable marked as final
except in declaration.使用 Java,您不能将任何内容分配给标记为final
的变量,除非在声明中。 On the other hand, you need these variable to be final to be used in this closure.另一方面,您需要这些变量是最终的才能在此闭包中使用。 This may feel frustrating after JS.这在 JS 之后可能会让人感到沮丧。 So what you may need to do with this particular code is to move variable declarations into closure, removing final
modifier.因此,您可能需要对这段特定代码做的是将变量声明移动到闭包中,删除final
修饰符。 If you still need to access them from outside, you are likely to define a class that implements Runnable
interface, and make these variable to be fields of this class instances though get methods.如果您仍然需要从外部访问它们,您可能会定义一个实现Runnable
接口的 class,并通过 get 方法使这些变量成为此 class 实例的字段。
Also, do you really need this code to run asynchronously?另外,你真的需要这段代码异步运行吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.