简体   繁体   中英

How can I get the class object from its member variable?

I'm currently working on this code, I want to pass an ID to a member function to get the object.

public class Car {

   private int _ID;
   private String name;
   private String model;

   Car(int _id, String name, String model){
       this._ID = _id;
       this.name = name;
       this.model = model;
   }

   ....

   public static Car getCar(int _id){
       Car mCar;
       //TODO: Algo to get car
       return mCar;
   }

}

Is there any way I can get the object in this way?

Any help is appreciated! Thank You!

You'll need to keep a Map of objects by key. Here's one way to do it:

public class Car {

   private int _ID;
   private String name;
   private String model;

   Car(int _id, String name, String model){
       this._ID = _id;
       this.name = name;
       this.model = model;
       carsById.put(_id, this);  // <-- add to map
   }

   ....

   private static Map<Integer, Car> carsById = new HashMap<>();

   public static Car getCar(int _id){
       return carsById.get(_id);
   }

}

There's no predefined way to do that. You'd have to have Car or something else maintain a Map<Integer,Car> or similar of cars. This would usually be best done not in Car itself, but in the code using it.

Unless you have a list (or map or tree or anything else suitable) of created Car , it's not possible with your current code only. A good practice is to separate this list out of Car class, maintained elsewhere. But if you insist, shmosel provides one way.

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