想象一下,我有一個類和其中的許多方法。 而在這些方法中,我正在創建對象。現在在許多方法中,我一次又一次地創建相同的方法。所以我想停止這些免費的對象創建。如何通過java中的方法將對象從一個類傳遞到另一個類
所以我使用的是一個工具類,我可以創建對象,並且可以將對象傳遞給特定的方法。
現在如何傳遞一個對象作爲參數以及如何在該方法中使用該對象?
示例代碼
public ProfileImpl(String profileId) {
Utilities.dbConnect();
if (dbClient.contains(profileId)) {
this.profile = dbClient.find(TOProfile.class, profileId);
}
}
@Override
public void setProfile(TOProfile profile) {
CouchDbClient dbClient = new CouchDbClient();
profile.set_rev(dbClient.update(profile).getRev());
this.profile = profile;
}
@Override
public void getProfile(TOProfile profile) {
CouchDbClient dbClient = new CouchDbClient();
profile.set_rev(dbClient.update(profile).getRev());
this.profile = profile;
}
您可以從目標與dbclient上面的代碼中看到的是一次又一次的創造。
Utility.java
public lass Utilities {
public static Object dbConnect(Object object) {
CouchDbClient dbClient = new CouchDbClient();
return dbClient;
}
}
現在我想通過這個對象,並使用它。 我是新來的java編碼,所以謝謝你的答案。
你能分享你真實的代碼嗎?或者真的有用的東西?我幾乎認爲你的類中沒有'setProfile'兩次,並且'getProfile'方法與'setProfile'方法完全相同,這沒什麼意義。 – Tom
是的,我剛剛複製,以顯示是否相同的對象將被創建multiplr次。如何傳遞對象作爲參數。那是我的問題。以避免多個對象創建。 –
所以你想傳遞CouchDbClient到setProfile方法?你的問題有點不清楚。 –