gpt4 book ai didi

java - 如何避免将此方法和所有其他变量设为静态?

转载 作者:太空宇宙 更新时间:2023-11-04 07:06:31 25 4
gpt4 key购买 nike

我对 Java 有点陌生,我正在尝试使用 swing 进行一些操作。

    class CustomListSelectionListener implements ListSelectionListener {
public void valueChanged (ListSelectionEvent e)
{
//All this listener does is to return the NAME of the selected connection to the static method gotocategories.
JList lsm = (JList)e.getSource();
Home.goToCategories((String)lsm.getSelectedValue());
}

问题是,监听器是一个类,所以基本上,如果我从“主类”调用静态方法,我需要将“goToCategories”函数中必须使用的所有变量设为静态。

    public static void goToCategories(String collectionname)
{
Statement stmt;
try
{
stmt = privconn.createStatement();
//Getting the collection ID;
String firststmt = "SELECT * FROM collection WHERE Name='"+collectionname+"' AND User_ID = "+userID+"";
ResultSet rs = stmt.executeQuery(firststmt);
rs.next();
int id = rs.getInt("ID");
JOptionPane.showMessageDialog(null, id);

} catch(Exception E)
{
E.printStackTrace();
}
}

这段代码有效,但我认为我正在创建很多静态变量,并且我不确定这是最好的方法。当然,一旦我尝试删除静态,它就会说“无法对非静态字段进行静态引用......”

最佳答案

如果您的 CustomSelectionListener 类具有对 Home 类的实例引用,您将能够在该实例上调用非静态方法。

它看起来像这样:

MyClass someObject = new MyClass();
someObject.nonStaticMethod();

但是,静态方法是在没有类实例的情况下通过使用类名称来调用的:

MyClass.someStaticMethod();

方法或成员变量是否应该是静态的是一个设计决策,正如注释所说,您应该完全理解 static 的含义,以便正确做出此决定。

关于java - 如何避免将此方法和所有其他变量设为静态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21293930/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com