如何在java中通过方法将对象从一个类传递到另一个类

如何在java中通过方法将对象从一个类传递到另一个类,java,Java,假设我有一个类和许多方法在里面。 在这些方法中,我正在创建对象。现在在许多方法中,我一次又一次地创建相同的方法。所以我想停止这些自由对象的创建 所以我使用了一个实用类,在这个类中我可以创建对象,并将对象传递给特定的方法 现在,如何将对象作为参数传递,以及如何在方法中使用该对象 示例代码 public ProfileImpl(String profileId) { Utilities.dbConnect(); if (dbClient.contains(profileId)) {

假设我有一个类和许多方法在里面。 在这些方法中,我正在创建对象。现在在许多方法中,我一次又一次地创建相同的方法。所以我想停止这些自由对象的创建

所以我使用了一个实用类,在这个类中我可以创建对象,并将对象传递给特定的方法

现在,如何将对象作为参数传递,以及如何在方法中使用该对象

示例代码

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编码新手,因此感谢您的回答。

您所谈论的东西通常被称为


几句话,,首先,您将使用返回
CouchDbClient
的方法
createCouchDbClient
定义一个
接口
,然后您将使用方法
createCouchDbClient
实现此接口,创建一个
,该方法真正创建对象
CouchDbClient
的实例类应该是这样的

public class Utilities {

    private static CouchDbClient dbClient;

    public static CouchDbClient dbConnect() {
        if(dbClient == null) {
            dbClient = new CouchDbClient();
        }
        return dbClient;
    }
}
然后,您可以根据需要多次调用
dbConnect
方法,如下所示

@Override
public void setProfile(TOProfile profile) {
    CouchDbClient dbClient = Utilities.dbConnect();
    profile.set_rev(dbClient.update(profile).getRev());
    this.profile = profile;
}

这里您的CouchDbClient对象只创建一次,可以多次使用。

您能分享真实的代码吗?还是真正有效的东西?我几乎不认为你的类中有两次
setProfile
,而且有一个与
setProfile
方法完全相同的
getProfile
方法没有多大意义。是的,我只是复制了它来显示是否要多次创建相同的对象。如何将对象作为参数传递。这是我的问题。避免创建多个对象。那么您想将CouchDbClient传递给setProfile方法吗?你的问题有点不清楚。你没有在方法中创建方法。不清楚你在问什么。我建议你正确格式化你的代码,据我所知,你的问题中有很多语法错误。