如何从Java中的静态方法访问非静态成员? [英] how to access a non static member from a static method in java?

查看:77
本文介绍了如何从Java中的静态方法访问非静态成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种情况,我必须从静态方法内部访问非静态成员.我可以使用新实例访问它,但是当前状态将丢失,因为非静态成员将被重新初始化.如何在不丢失数据的情况下实现这一目标?

I have a situation where i have to access a non static member from inside a static method. I can access it with new instance, but current state will be lost as non static member will be re-initialized. How to achieve this without losing data?

推荐答案

也许您想要单人.然后,您可以从静态方法中获取该类的(唯一)实例并访问其成员.

Maybe you want a singleton. Then you could get the (only) instance of the class from within a static method and access its members.

基本思想是

public class Singleton {
  private static Singleton instance = null;

  private Singleton() {}

  public static Singleton getInstance() {
    if (instance == null) {
        instance = new Singleton();
    }
    return instance;
  }
}

,然后使用某些静态方法:

and then in some static method:

public static someMethod() {
    Singleton s = Singleton.getInstance();
    //do something with s
}

这篇关于如何从Java中的静态方法访问非静态成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆