英文:
How do I use a Singleton instance in other classes
问题
以下是你提供的代码的中文翻译部分:
我在下面使用了单例模式来创建一个用户,以便我的程序能意识到用户已登录。我试图在我的 JavaFx 程序的不同页面中显示用户名,因此我希望能从多个类中的实例中使用用户名详细信息。当我尝试使用 `Usersession.toString` 时,它显示非静态方法不能在静态上下文中使用的错误。我该如何解决这个问题?
public final class UserSession {
    private static UserSession instance;
    private String userName;
    private UserSession(String userName) {
        this.userName = userName;
    }
    public static UserSession getInstance(String userName) {
        if(instance == null) {
            instance = new UserSession(userName);
        }
        return instance;
    }
    public String getUserName() {
        return userName;
    }
    public void cleanUserSession() {
        userName = ""; // 或者 null
    }
    @Override
    public String toString() {
        return "UserSession{" +
                "userName='" + userName + "'}";
    }
}
英文:
I'm using the Singleton pattern below to create a user so that my program will be aware that a user is logged in. I'm trying to show the username in different pages of my JavaFx program so I want to use the username details from the instance in multiple classes. When I try to use Usersession.toString, it says that a non-static method cannot be used in a static context. How do I fix this?
public final class UserSession {
    private static UserSession instance;
    private String userName;
    private UserSession(String userName) {
        this.userName = userName;
    }
    public static UserSession getInstace(String userName) {
        if(instance == null) {
            instance = new UserSession(userName);
        }
        return instance;
    }
    public String getUserName() {
        return userName;
    }
    public void cleanUserSession() {
        userName = "";// or null
    }
    @Override
    public String toString() {
        return "UserSession{" +
                "userName='" + userName + "}";
    }
}
答案1
得分: 0
实际上,您试图在没有其实例的情况下访问方法。
正确的方法如下:
UserSession.getInstace("您的用户名详细信息").toString();
然后根据您的toString()方法,它将返回如下详细信息:
UserSession{userName='您的用户名详细信息'}
英文:
Actually you trying to access method without its instance .
Right way to do it as below:
UserSession.getInstace("your username details").toString();
then it will return below details as per your toString() method:
UserSession{userName='your username details}
专注分享java语言的经验与见解,让所有开发者获益!



评论