在Java中将字符串解析为对象
我创建了一个包含两个类的项目:产品和库存。 现在我创建了一个第三类菜单来与我的两个类交互 我正在将JOptionPane与showInputDialog一起使用。 我想从我自己创建的类中获取类型产品的输入 我知道有一种方法可以将输入字符串解析为整数在Java中将字符串解析为对象,java,class,input,Java,Class,Input,我创建了一个包含两个类的项目:产品和库存。 现在我创建了一个第三类菜单来与我的两个类交互 我正在将JOptionPane与showInputDialog一起使用。 我想从我自己创建的类中获取类型产品的输入 我知道有一种方法可以将输入字符串解析为整数 int keuze = Integer.parseInt(input); 所以我正在寻找一种等效的方法来实现这一点 private void addNewProductType() { String input = JOpt
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的代码,您将看到它自己将字符串转换为整数。您必须自己做:在产品类上编写一个解析方法,从字符串创建一个解析方法
有一些通用库可以使用反射将JSON转换为对象,但字符串输入需要采用正确的格式,这对于您的应用程序来说相当重要。没有默认方法来创建字符串形式的对象,因为此操作因类而异。您必须自己通过解析对象字段的字符串并分配它们来定义此行为 例如,如果您有这样一个类产品: 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);
}
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);
}