![](/img/trans.png)
[英]Given a class member name or object, how can I find its declaring/enclosing class object in java?
[英]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.