Home > Blockchain >  Generic Return Types
Generic Return Types

Time:02-17

Would there be a better way to write this getInput() method instead of checking for every single class that could be passed in?

    public Object getInput(String prompt, Class<?> type) {
        System.out.print(prompt);
        Scanner scn = new Scanner( System.in );
        String str = scn.nextLine( );
        if(type.equals(Integer.class))
            return Integer.parseInt(str);
        else if (type.equals(Double.class))
            return Double.parseDouble(str);
        else if (type.equals(Boolean.class))
            return Boolean.parseBoolean(str);
        else return type.cast(str);
    }

It works enough, but I would like to make it work with mostly all cases without having to add many more else if statements. As well as this, I am required to cast to that type when I take the input and assign it to a variable. Is there a way I could get around this?

Invocation:
int num = (int)menu.getInput("Enter an integer: ", Integer.class);

CodePudding user response:

There's a few ways you "might" do this, but probably one of the ways which won't have you modifying the "base" input method every time you want a new input type, would be to inject the "parsing" workflow into the method itself.

That is, create a generic interface which defines a "parse" method which can take a String and return value of a specific type and pass that to your input method, for example...

import java.util.Scanner;

public final class Main {

    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        Integer result = getInput("Please enter an integer: ", new IntParser());
    }

    public interface Parsable<T> {
        public T parse(String value);
    }

    public class IntParser implements Parsable<Integer> {
        @Override
        public Integer parse(String value) {
            return Integer.parseInt(value);
        }
    }

    public <T> T getInput(String prompt, Parsable<T> parser) {
        System.out.print(prompt);
        Scanner scn = new Scanner(System.in);
        String str = scn.nextLine();

        return parser.parse(str);
    }
}

Now, if you didn't want to have to type getInput("Please enter an integer: ", new IntParser()); every time

  • Related