vendredi 1 avril 2016

Java get valueOf for generic subclass of java.lang.Number or primitive

After reading through a lot of questions, I asked myself if it is possible to solve the dilemma of transforming a string into a generic number WITHOUT using a hardcoded approach.

For example: I get from a method a parameter with the type Class With Number.isAssignableFrom or other ways I can check, if this is a number class. But I also get from the user an input. As a string.

The question is: Can I now somehow transform this string into the requested number object without building an if statement for every case?

Example code, properly not working:

Object ret = null;

for(int i=0;i<method.getParameterTypes().length; i++ ) {
    Class<?> param = method.getParameterTypes()[i];
    String argString = getUserInput(_in, "Argument ("+param.getSimpleName()+"): ");

    if( Number.isAssignableFrom(param) )
        ret = ((Class<NumberChild>)param).valueOf(argString);
    /// OR
        ret = param.cast( Double.valueOf(argString) )
}

The even advance this question: Could it be possible to cast every primitive in something similar in from the above way?

Note: The approach here should completely focus on a non hardcoded solution. My currently running code uses the approach of hardcoding every single case. But in those cases a more general solution would be much more interesting.





Aucun commentaire:

Enregistrer un commentaire