繁体   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