简体   繁体   中英

Parse String to Object in Java

I created a project with 2 classes, Product and Stock. Now I created a third class "Menu" to interact with my 2 classes.

I'm using JOptionPane with the showInputDialog. I'd like to get the input to the type "Product" from my self created class.

I know there's a way to parse the input (String) to an Integer.

int keuze = Integer.parseInt(input);

So I'm searching an equivalent way to do this.

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

   }

Not really, no. If you look in the code for Integer.parseInt() you'll see that it does its own work in turning the string into an integer. You'll have to do your own: write a parse() method on your Product class that creates one from a String .

There are general purpose libraries that convert from JSON to objects, using reflection, but the String input needs to be in the right format, and this sounds rather heavyweight for your application.

There is no default method to create an Object form a string because this operation varies from class to class. You must define this behavior yourself by parsing the String for the object's fields and assigning them.

For example, if you have a class Product like so:

class Product {
    String name;
    int id;

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

An addNewProduct() function would look like:

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);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM