简体   繁体   English

如何从Java中的静态方法访问非静态成员?

[英]how to access a non static member from a static method in 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. 然后,您可以从静态方法中获取该类的(唯一)实例并访问其成员。

The basic idea is 基本思想是

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
}

What you are asking for doesn't really make sense. 您所要的并没有任何意义。 Just make your method non-static because your static method cannot be tied to an instance. 只需将您的方法设为非静态即可,因为您的静态方法无法绑定到实例。

Static methods do not apply to a particular instance/object, they're a class-level thing. 静态方法不适用于特定的实例/对象,它们是类级别的东西。 Because of that, they're not given an instance reference. 因此,没有为他们提供实例引用。 So, no you cannot do this. 因此,不,您不能这样做。

If you can work out which instance reference to use another way, you could access the non-static methods of it. 如果您可以算出哪个实例引用使用其他方式,则可以访问它的非静态方法。

Or, alternatively, re-architect your classes so that it's a non-static method. 或者,可以重新构造您的类,使其成为非静态方法。

You can't. 你不能 A static method is not associated with any particular state (aka any non-static members). 静态方法不与任何特定状态(也称为任何非静态成员)相关联。 In other words, they operate independently of any particular instance of the class so they cannot depend on non-static members. 换句话说,它们独立于类的任何特定实例进行操作,因此它们不能依赖于非静态成员。

A non static member variable "is state". 非静态成员变量“是状态”。 It's the state of a specific instance of that class. 它是类特定实例状态。

When you say you want to access a non-static member variable, it's as good as saying "want to access a non-static member variable of a specific instance of class XXX ", I mean the bolded part is implicit. 当您说要访问非静态成员变量时,就像说“要访问类XXX的特定实例的非静态成员变量”一样好,我的意思是粗体部分是隐式的。

So it doesn't make sense to say "I can access it with new instance". 因此,说“我可以使用新实例访问它”没有任何意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM