簡體   English   中英

用Java將字符串解析為對象

[英]Parse String to Object in Java

我創建了一個產品和庫存兩個類的項目。 現在,我創建了一個第三類“菜單”來與我的兩個類進行交互。

我正在將JOptionPane與showInputDialog一起使用。 我想從我自己創建的類中獲取“產品”類型的輸入。

我知道有一種方法可以將輸入(字符串)解析為整數。

int keuze = Integer.parseInt(input);

所以我正在尋找一種等效的方法來做到這一點。

 private void addNewProductType()
   {
        String input = JOptionPane.showInputDialog("Which product do you want to add?\n");
        stock.addNewProduct(input);

   }

不是,不是 如果您查看Integer.parseInt()的代碼,您會發現它在將字符串轉換為整數方面發揮了自己的作用。 您必須自己做:在Product類上編寫一個parse()方法,該方法從String創建一個。

有一些通用庫可以使用反射將其從JSON轉換為對象,但是String輸入必須采用正確的格式,這對於您的應用程序來說是相當沉重的。

沒有默認的方法來創建string形式的Object因為此操作因類而異。 您必須自己解析該行為,方法是解析對象字段的String並分配它們。

例如,如果您有一個類似這樣的Product類:

class Product {
    String name;
    int id;

    public Product(String name, int id) {
        this.name = name;
        this.id = id;
    }
}

一個addNewProduct()函數如下所示:

Product addNewProduct(String str) {
    String name;
    int id;

    // parse the String to get name and id
    // e.g. if str = "Ball 352", isolate "Ball" and "352" and
    // use parseInt() on "352" to get the id

    return new Product(name, id);

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM