以某种方式将方法或匿名内部类放入驱动程序类的主要方法中有一个特殊的习惯用法:
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 的实例化放入......我不太确定。也许以上是正确的和“好的”?