繁体   English   中英

如何从其成员变量中获取类对象?

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

我目前正在处理此代码,我想将ID传递给成员函数以获取对象。

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;
   }

}

有什么办法可以这样获得对象吗?

任何帮助表示赞赏! 谢谢!

您需要按键保存对象Map 这是一种实现方法:

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);
   }

}

没有预定义的方法可以做到这一点。 您必须拥有Car或其他东西来维护Map<Integer,Car>或类似的汽车。 通常最好不要Car本身中,最好在使用它的代码中完成。

除非您具有创建的Car的列表(或地图,树或其他合适的东西),否则仅使用当前代码是不可能的。 好的做法是将此列表从Car类中分离出来,并在其他位置进行维护。 但是,如果您坚持认为,shmosel提供了一种方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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