“无法从静态上下文中引用非静态变量"的解决方法是什么? [英] what is the work-around to "non-static variable cannot be referenced from a static context"?

查看:224
本文介绍了“无法从静态上下文中引用非静态变量"的解决方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将方法或匿名内部类以某种方式放入驱动程序类的主要方法中是一个特殊的习惯:

There's a particular idiom to putting a method, or perhaps anonymous inner class, somehow, into the main method of a driver class:

package net.bounceme.dur.misc;

import net.bounceme.dur.misc.Foo;

public class StaticRef {

    Foo f = Foo.INSTANCE;

    public static void main(String[] args) throws Exception {

        f.connect();  //move this to inside "run"
        /*
        public void run(){
           StaticRef sf = new StaticRef();
           //do stuff here
        }
         */
    }
}

为防止出现以下错误:

init:
Deleting: /home/thufir/NetBeansProjects/nntp/build/built-jar.properties
deps-jar:
Updating property file: /home/thufir/NetBeansProjects/nntp/build/built-jar.properties
Compiling 1 source file to /home/thufir/NetBeansProjects/nntp/build/classes
/home/thufir/NetBeansProjects/nntp/src/net/bounceme/dur/misc/StaticRef.java:11: non-static variable f cannot be referenced from a static context
        f.connect();  //move this to inside "run"
1 error
/home/thufir/NetBeansProjects/nntp/nbproject/build-impl.xml:626: The following error occurred while executing this line:
/home/thufir/NetBeansProjects/nntp/nbproject/build-impl.xml:245: Compile failed; see the compiler error output for details.
BUILD FAILED (total time: 0 seconds)

但是,到目前为止,我什么都找不到.我在线程示例中看到了类似的内容,但是不能完全理解语法.

However, I can't find anything so far. I see something similar in threading examples, but can't quite get the syntax.

以下内容基本上是我想要的,但我认为这是不正确的:

The following is largely what I want, but I don't think it's quite correct:

package net.bounceme.dur.misc;

public class StaticRef {

    Foo f = Foo.INSTANCE;

    public static void main(String[] args) throws Exception {

        StaticRef sf = new StaticRef();
        sf.f.connect();
    }
}

我想将sf的实例化放入...我不太确定.也许以上是正确的,还可以"吗?

What I would like is to put the instantiation of sf into...I'm not quite sure. Maybe the above is correct and "ok"?

推荐答案

如果此代码有缺陷"或违反任何OOP原则,请发表评论:

If this code is "faulty" or violates any OOP principle, please do comment:

package net.bounceme.dur.misc;

public class StaticRef {

    private Foo f = Foo.INSTANCE;

    public StaticRef() throws Exception {
        f.connect();
    }

    public static void main(String[] args) throws Exception {
        new StaticRef();
    }
}

我听说过这种方法的理由是,对于重复使用,只需删除main方法就可以轻松地将StaticRef修改为Java Bean.请发表评论. 另请参阅此答案,以获取类似的解决方案,或

The justification I've heard for this approach is that, for re-use, StaticRef can be easily modified to act as a Java Bean by doing little more than removing the main method. Please do comment. See also this answer, for a similar solution, or this other answer.

这篇关于“无法从静态上下文中引用非静态变量"的解决方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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