Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - How do I pass the return type of a method as parameter?

Tags:

java

I'm trying to make a small game with a TUI. The TUI should have a get() method that should take a String question and a return type as parameter, so you can use it to request an object.

For example, get("What is your name?", String) should return a String and get("What color do you want?", Color) should return a Color.

This is what I've come up with:

public interface View {

    public <T> T get(String question, Class<T> type) throws InputException;

}

public class TUI implements View {

    public Color get(String question, Class<Color> type) {
        // code
    }

    public String get(String question, Class<String> type) {
        // code
    }

}

Color color = Game.getView().get("What piece do you want to place?", Color.class);

Unfortunately, the methods in TUI are not accepted as implementations of public <T> T get(String question, Class<T> type) throws InputException;. Is there any way I can do this?

like image 622
HYBR1D Avatar asked Oct 20 '25 13:10

HYBR1D


1 Answers

Keeping it type safe by splitting the functions would seem more appropriate:

Color color = Game.getView().getColor("What piece do you want to place?");
String string = Game.getView().getString("What piece do you want to place?");
like image 130
Alan Blyth Avatar answered Oct 23 '25 02:10

Alan Blyth