将对象数组转换为字符串数组

Converting object array to string array

我有一个商品 class,其中包含商品名称、价格等数据,当卖家想卖东西时我会添加它,例如:

public void sellItem(String itemName, double Price) throws java.rmi.RemoteException, Exception {
    items.add(new Item(itemName, price)); 

我然后return列表中的所有项目,所以seller/buyer可以浏览列表。

public ArrayList<Item> listItems() {
    return items;
}

接下来,我将致力于填充 JGroups 实例,以允许跨实例复制此 'Item' 数据。列出项目后,我转换为对象:

/* Create a new ItemObject containing the Items used for JGroups later */
public void createItemObject() throws Exception {
    Object[] objArray = items.toArray();
    FileOutputStream fis = new FileOutputStream("io");
    ObjectOutputStream itemObject = new ObjectOutputStream(fis);
    itemObject.writeObject(objArray);
    itemObject.close();
    fis.close();
}

复制服务器的每个实例都将把这个对象作为输入,并希望将这个对象中的数据打印到它的终端window:

static Object io = new Object();
public static void getAuctionObject() throws Exception {

    FileInputStream fis = new FileInputStream("io");
    ObjectInputStream auctionObjectIn = new ObjectInputStream(fis);
    ao = auctionObjectIn.readObject();
    auctionObjectIn.close();
    System.out.println("Received object at Front End:  " + ao);
    //Print out item data.....
}

但是,我将如何实际遍历此对象并打印出项目数据,例如 'itemName'、'price' 等?

覆盖对象上的 toString() 方法,以便每个类型 returns 格式正确的字符串。

或者,如果您想保持原始 toString() 方法不变,请创建一个新的 interface,它由您要打印的所有对象类型共享,并提供相同的 "shared method" 通过所有这些对象,每个对象类型指定接口方法的行为。