79798342

Date: 2025-10-24 02:50:02
Score: 1
Natty:
Report link

Extensible solution

You asked for an extensible type parser.

This is by no means tested and probably has typos in it, but maybe it can get you started. I am just typing in a hurry what I understand from the comment by @Anonymous: Building a parser where you can plug in conversions for types. The parser looks a converter for the type asked for up in a map. And then has that converter perform the actual parsing into the type in question.

public class TypeParser {
    private Map<Class<?>, Function<String, Class<?>> converters = new HashMap<>();

    public <T extends Comparable> registerConverter(
            Class<T> type, Function<String, Class<T>> converter) {
        converters.put(type, converter);
    }

    public <T> static T convertStringToTypeOf(String raw, Class<T> type){
        return type.cast(converters.get(type).apply(raw));
    }
}

Use like

    TypeParser myParser = new TypeParser();
    myParser.registerConverter(String.class, s -> s);
    myParser.registerConverter(Integer.class, Integer::valueOf);
    // ...

    Integer myInteger = myParser.convertStringToTypeOf("42", Integer.class);
Reasons:
  • Long answer (-1):
  • Has code block (-0.5):
  • Unregistered user (0.5):
  • User mentioned (1): @Anonymous
  • Low reputation (1):
Posted by: Mayara Collets