【发布时间】:2013-02-02 13:55:49
【问题描述】:
将方法或匿名内部类以某种方式放入驱动程序类的 main 方法有一个特殊的习惯:
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)
但是,到目前为止我找不到任何东西。我在线程示例中看到了类似的内容,但无法完全理解语法。
以下大部分是我想要的,但我认为它不太正确:
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 的实例化放入...我不太确定。也许上面是正确的并且“ok”?
【问题讨论】:
-
在您的示例中, Foo 不是静态的。 f.connect() 将不起作用。您的问题是“我如何在公共静态主体中调用 f.connect()?”。如果是这样,你不能不创建一个 StaticRef 的实例。
-
对不起,是的,Foo 不是静态的,我也不希望它是静态的。在不声明它是静态或最终的情况下实例化 Foo 的解决方法是什么?我会修改问题,我可能搞混了。
-
@Thufir。在您更新问题之后,我现在真的不明白您想要什么。因为您更新后的代码可以正常工作。
-
Foo f =前面缺少静态以允许写入sf.f.connect()... -
只是引用 Foo 实例有点尴尬,我宁愿它不是静态的也不是最终的,只有私有的。我相信有一个“可运行”使用的习语,我也在 Swing 生成的代码中看到过。
标签: java oop javabeans static-methods idioms