Coat
Coat

Reputation: 717

Casting Function Return Type Based on Class Field

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?

Upvotes: 1

Views: 599

Answers (1)

shmosel
shmosel

Reputation: 50716

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);
    }
}

Upvotes: 3

Related Questions