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

Java 如何避免将此方法和所有其他变量设置为静态?,java,swing,static,listener,jlist,Java,Swing,Static,Listener,Jlist,我对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 sta

我对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());
    }
问题是,侦听器是一个类,所以基本上如果我从“home类”调用一个静态方法,我需要使“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();

方法或成员变量是否应该是静态的是一个设计决策,正如评论所说的那样,为了正确地做出这个决策,您应该充分理解
静态
的含义。

我认为最好的方法是创建一个没有主方法的类,

在构造函数中完成所有工作,然后从另一个类(new my class)中的主方法创建该类的新实例,

您应该仔细阅读并准确理解
static
的含义。是很好的推荐人。注意:你不想。或者像Hibernate那样为你处理所有这些东西的库。我确实理解你写的东西,我在这里选择了第二个选项。我想了解的是:在内存使用方面,什么更好?实例化对象确实会消耗内存,与存储对象成员的数据所需的内存成比例。