Home Casting Function Return Type Based on Class Field
Reply: 1

Casting Function Return Type Based on Class Field

Coat
1#
Coat Published in 2018-02-14 00:52:15Z

I've got a class that looks something like.

public class ParseValue {
  public String value;
  public final Class classType;
}

And I'd like to make a function that does a conversion and returns a casted value.

public T parseValue(ParseValue parseInfo) {
  if(parseInfo.classType == String.class) {
    return parseInfo.value;
  } else if (parseInfo.classType == Double.class) {
    return Double.valueOf(parseInfo.value);
  }
}

Right now I can have this function return an Object and then cast it upon getting the result, but is there a way to make the function do the cast based on the input ParseValue's classType field?

shmosel
2#
shmosel Reply to 2018-02-14 01:03:15Z

The safest way to do it is to make ParseValue generic:

public class ParseValue<T> {
    public String value;
    public final Class<T> classType;

    public T parseValue() {
        Object result;
        if (classType == String.class) {
            result = value;
        } else if (classType == Double.class) {
            result = Double.valueOf(value);
        } else {
            throw new RuntimeException("unknown value type");
        }
        return classType.cast(result);
    }
}
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.332947 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO