在Java中,我做了类似下面的事情而没有考虑太多:
public class Main {
public void run() {
// ...
}
public static void main(String[] args) {
new Main().run();
}
}
Run Code Online (Sandbox Code Playgroud)
然而,最近我不确定这样做是否安全.毕竟,在Main创建对象之后没有对该对象的this引用(好吧,有引用,但这会计数吗?),所以看起来垃圾收集器可能会在执行过程中删除对象的危险一些东西.所以也许这个main方法应该是这样的:
public static void main(String[] args) {
Main m = new Main();
m.run();
}
Run Code Online (Sandbox Code Playgroud)
现在,我敢肯定的是,第一个版本的作品,我从来没有任何问题,但我想知道,如果它是安全的.所有的情况下做的(不仅是在一个特定的JVM,但最好根据语言规范对此类案例的说法).
我遇到的代码就是这样,创建了一个对象并调用了它的方法:
public static void main(String[] args) {
new DemoSoap().request(); //<----how come there is no reference?
}
private void request() {
try {
// Build a SOAP message to send to an output stream.
SOAPMessage msg = create_soap_message();
// Inject the appropriate information into the message.
// In this case, only the (optional) message header is used
// and the body is empty.
SOAPEnvelope env = msg.getSOAPPart().getEnvelope();
SOAPHeader hdr = env.getHeader();
// Add an element to the SOAP header.
Name lookup_name …Run Code Online (Sandbox Code Playgroud)