简体   繁体   中英

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. 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. On the other hand, you need these variable to be final to be used in this closure. This may feel frustrating after JS. So what you may need to do with this particular code is to move variable declarations into closure, removing final modifier. 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.

Also, do you really need this code to run asynchronously?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM