简体   繁体   中英

Find object created inside a method in other class

For example, 2 class: Ticket and Customer

public class Ticket{
 private String cstName; 
public Ticket(String name){
   this.cstName = name; 
 }
}

public class Customer{
private String name;
public void book(){
Ticket t = new Ticket(t); 
}
}

How can I find and use t object elsewhere???

What you ask for is completely impossible. An object is made, the object is assigned to a local variable, and the method ends.

As the method ends, all local variables (and t is a local variable), immediately go into the bin and there is nothing in java that lets you 'plug into' this process or that lets you stop this process. The variable is just gone.

The object is still on the heap somewhere, but no longer accessible. Eventually it will be garbage collected. There's nothing you can do about that, either. Java does not have a 'list all objects in the heap' method and never will.

You can mess with reference queues which is an extremely advanced topic that in no way is suitable given the way this question is stated, and wouldn't work for arbitrary methods like this.

If you control the code of Ticket itself you can save the reference as part of the constructor, which would be extremely bad design, and would have nothing at all to do with the notion of t , or that the book method made it.

What you presumably want, is a field:

public class Customer {
  private String name;
  private Ticket ticket;

  public void book() {
    this.ticket = new Ticket(t); 
  }

  public Ticket getTicket() {
    return this.ticket;
  }
}

and now you could do:

Customer c = new Customer();
c.book();
Ticket t = c.getTicket();

or perhaps do:

public class Customer {
  private String name;
  private Ticket ticket;

  public Ticket book() {
    this.ticket = new Ticket(t); 
    return this.ticket;
  }
}

and now you could do:

Customer c = new Customer();
Ticket t = c.book();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM