![](/img/trans.png)
[英]“Cannot refer to the non-final local variable defined in an enclosing scope.” after changing Execution Environment
[英]Problems with local variable scope. How to solve it?
我嘗試在我的代碼中執行statemet.executeUpdate()
時收到以下錯誤:
Local variable statement defined in an enclosing scope must be final or effectively final.
到目前為止這是我的代碼:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;.
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
public class a1 {
protected Shell shell;
private Text text;
private Text text_1;
private Text text_2;
private Text text_3;
/**
* Launch the application.
* @param args
*/
public static void main(String[] args) {
try {
a1 window = new a1();
window.open();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Open the window.
*/
public void open() {
Display display = Display.getDefault();
createContents();
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
/**
* Create contents of the window.
*/
protected void createContents() {
Connection connect = null;
ResultSet resultSet = null;
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
connect = DriverManager.getConnection("jdbc:mysql://localhost/railwaydb", "root", "");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Statement statement = null;
// statements allow to issue SQL queries to the database
try {
statement = connect.createStatement();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
shell = new Shell();
shell.setSize(450, 300);
shell.setText("SWT Application");
Label lblName = new Label(shell, SWT.NONE);
lblName.setBounds(10, 43, 47, 15);
lblName.setText("Name");
Label lblFrom = new Label(shell, SWT.NONE);
lblFrom.setBounds(10, 74, 55, 15);
lblFrom.setText("From");
Label lblTo = new Label(shell, SWT.NONE);
lblTo.setBounds(10, 105, 55, 15);
lblTo.setText("To");
Label lblPrice = new Label(shell, SWT.NONE);
lblPrice.setBounds(10, 137, 55, 15);
lblPrice.setText("Price");
text = new Text(shell, SWT.BORDER);
text.setBounds(64, 43, 76, 21);
text_1 = new Text(shell, SWT.BORDER);
text_1.setBounds(64, 74, 76, 21);
text_2 = new Text(shell, SWT.BORDER);
text_2.setBounds(64, 105, 76, 21);
text_3 = new Text(shell, SWT.BORDER);
text_3.setBounds(64, 137, 76, 21);
Label lblRailwayDatabase = new Label(shell, SWT.NONE);
lblRailwayDatabase.setBounds(174, 10, 97, 15);
lblRailwayDatabase.setText("Railway Database");
Label lblCreateView = new Label(shell, SWT.NONE);
lblCreateView.setBounds(189, 43, 76, 15);
lblCreateView.setText("Create View");
Button btnName = new Button(shell, SWT.CHECK);
btnName.setBounds(189, 73, 93, 16);
btnName.setText("Name");
Button btnFrom = new Button(shell, SWT.CHECK);
btnFrom.setBounds(189, 105, 93, 16);
btnFrom.setText("From");
Button btnTo = new Button(shell, SWT.CHECK);
btnTo.setBounds(189, 137, 93, 16);
btnTo.setText("To");
Button btnPrice = new Button(shell, SWT.CHECK);
btnPrice.setBounds(189, 171, 93, 16);
btnPrice.setText("Price");
Button btnInsert = new Button(shell, SWT.NONE);
btnInsert.addMouseListener(new MouseAdapter() {
@Override
public void mouseDown(MouseEvent e) {
String name = text.getText();
String from = text_1.getText();
String to = text_2.getText();
String price = text_3.getText();
String query = "INSERT INTO booking (name, fromst, tost, price) VALUES ('"+name+"', '"+from+"', '"+to+"', '"+price+"')";
try {
statement.executeUpdate(query);
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
btnInsert.setBounds(10, 171, 75, 25);
btnInsert.setText("Insert");
Button btnView = new Button(shell, SWT.NONE);
btnView.setBounds(307, 74, 75, 25);
btnView.setText("View");
Button btnIndex = new Button(shell, SWT.NONE);
btnIndex.setBounds(307, 127, 75, 25);
btnIndex.setText("Index");
}
}
我也嘗試設置statement
final,但聲明給了我另一個錯誤。
你確實有一個范圍問題,因為statement
是這里定義的本地方法變量:
protected void createContents() {
...
Statement statement = null; // local variable
...
btnInsert.addMouseListener(new MouseAdapter() { // anonymous inner class
@Override
public void mouseDown(MouseEvent e) {
...
try {
statement.executeUpdate(query); // local variable out of scope here
} catch (SQLException e1) {
e1.printStackTrace();
}
...
});
}
當您嘗試在mouseDown()
方法中訪問此變量時,您嘗試從匿名內部類中訪問本地變量,並且范圍不夠。 所以它絕對必須是final
(由於代碼不可能)或聲明為類成員,因此內部類可以訪問此statement
變量。
資料來源:
使statement
成為類成員而不是局部變量:
public class A1 { // Note Java Code Convention, also class name should be meaningful
private Statement statement;
...
}
定義另一個最終變量並使用這個變量,如@HotLicks所建議:
protected void createContents() {
...
Statement statement = null;
try {
statement = connect.createStatement();
final Statement innerStatement = statement;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
...
}
重新考慮你的方法。 如果在按下btnInsert
按鈕之前不會使用statement
變量,那么在實際發生之前創建連接是沒有意義的。 你可以使用這樣的所有局部變量:
btnInsert.addMouseListener(new MouseAdapter() {
@Override
public void mouseDown(MouseEvent e) {
try {
Class.forName("com.mysql.jdbc.Driver");
try (Connection connect = DriverManager.getConnection(...);
Statement statement = connect.createStatement()) {
// execute the statement here
} catch (SQLException ex) {
ex.printStackTrace();
}
} catch (ClassNotFoundException ex) {
e.printStackTrace();
}
});
首先,我們只是不能使變量最終,因為它的狀態可能在程序運行期間發生變化,而我們在內部類覆蓋中的決定可能取決於其當前狀態。
其次,良好的面向對象編程實踐建議僅使用對類定義至關重要的變量/常量作為類成員。 這意味着如果我們在匿名內部類覆蓋中引用的變量只是一個實用變量,那么它不應該在類成員中列出。
但是 - 從Java 8開始 - 我們有第三個選項,在這里描述:
https://docs.oracle.com/javase/tutorial/java/javaOO/localclasses.html
從Java SE 8開始,如果在方法中聲明本地類,它可以訪問方法的參數。
所以現在我們可以簡單地將包含新內部類及其方法的代碼覆蓋到私有方法中,該方法的參數包括我們從覆蓋內部調用的變量。 然后在btnInsert聲明語句之后調用此靜態方法: -
. . . .
. . . .
Statement statement = null;
. . . .
. . . .
Button btnInsert = new Button(shell, SWT.NONE);
addMouseListener(Button btnInsert, Statement statement); // Call new private method
. . .
. . .
. . .
private static void addMouseListener(Button btn, Statement st) // New private method giving access to statement
{
btn.addMouseListener(new MouseAdapter()
{
@Override
public void mouseDown(MouseEvent e)
{
String name = text.getText();
String from = text_1.getText();
String to = text_2.getText();
String price = text_3.getText();
String query = "INSERT INTO booking (name, fromst, tost,price) VALUES ('"+name+"', '"+from+"', '"+to+"', '"+price+"')";
try
{
st.executeUpdate(query);
}
catch (SQLException e1)
{
e1.printStackTrace(); // TODO Auto-generated catch block
}
}
});
return;
}
. . . .
. . . .
. . . .
不是錯誤:
JSONObject json1 = getJsonX();
錯誤:
JSONObject json2 = null;
if(x == y)
json2 = getJSONX();
錯誤: 在封閉范圍中定義的局部變量語句必須是最終的或有效的最終。
但你可以這樣寫:
JSONObject json2 = (x == y) ? json2 = getJSONX() : null;
我發現這種方法很有用。 這樣你就不需要課,也不需要最終
btnInsert.addMouseListener(new MouseAdapter() {
private Statement _statement;
public MouseAdapter setStatement(Statement _stmnt)
{
_statement = _stmnt;
return this;
}
@Override
public void mouseDown(MouseEvent e) {
String name = text.getText();
String from = text_1.getText();
String to = text_2.getText();
String price = text_3.getText();
String query = "INSERT INTO booking (name, fromst, tost, price) VALUES ('"+name+"', '"+from+"', '"+to+"', '"+price+"')";
try {
_statement.executeUpdate(query);
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}.setStatement(statement));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.