Java:在没有引用的情况下在堆中创建对象的目的是什么

Lut*_*her 1 java heap garbage-collection object

我遇到的代码就是这样,创建了一个对象并调用了它的方法:

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 = create_qname(msg);
         hdr.addHeaderElement(lookup_name).addTextNode("time_request");

         // Simulate sending the SOAP message to a remote system by
         // writing it to a ByteArrayOutputStream.
         out = new ByteArrayOutputStream();
         msg.writeTo(out);

         trace("The sent SOAP message:", msg);

         SOAPMessage response = process_request();
         extract_contents_and_print(response);
       }
       catch(SOAPException e) { System.err.println(e); }
       catch(IOException e) { System.err.println(e); }
    }
Run Code Online (Sandbox Code Playgroud)
  • 在request()方法之后,对象是否会被garbace集合破坏?
  • 在没有引用的情况下在堆中创建对象有什么好处,就像在这种情况下一样?

Den*_*ret 5

关键是能够调用该request方法.

是的,一旦语句结束,对象就可以被吞噬.

请注意,在此代码中,由于对象是在没有参数的情况下初始化的,除非有其他构造函数或方法,否则该方法似乎应该是静态的:实例似乎完全没用.

  • @Luther:如果你不使用它,有什么好处?没有一个的优点是它避免了无用的变量,并减少了对象的范围. (2认同)