我遇到的代码是这样的,创建了一个对象并调用了它的方法:
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/