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

标签 java object garbage-collection heap-memory

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

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); }
    }
  • 对象是否会在执行后被垃圾收集器销毁 request() 方法?
  • 在这种情况下,在堆中创建一个没有引用的对象有什么好处?

最佳答案

重点是能够调用request方法。

是的,只要语句结束,对象就可以被丢弃。

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

关于Java:在没有引用的情况下在堆中创建对象的目的是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17697048/

相关文章:

javascript - 所有对象属性不为空的javascript

garbage-collection - 垃圾收集瓶颈的示例

java - 在使用 Streams API 时使用 Chronicle Map 产生垃圾

java - 当我的accept-count=100000时,为什么会出现SocketTimeoutException?

javascript - JSON解码: Mixed types - not valid syntax error

java - 如何修复 'Element ns1:WS_PersonaGetActEmpresarial.Execute has a relative namespace: ns1="DGI_Modernizacion_Consolidado

c++ - 错误 : No matching function for call to 'fraction::add(fraction&, fraction&)'

c# - 我如何才能发现第 0 代堆中有哪些可终结对象?

java - DynamoDB Java SDK 如何使用 NOT EQUALS 查询字符串字段

java - Selenium webdriver :org. openqa.selenium.InvalidElementStateException:元素已禁用,因此可能无法用于操作