简体   繁体   中英

Casting Generic Types in Java (e.g. T value = (T) inputParam)

I have a very simple question but it seems nobody has answered it before.

I need to make a cast from an object to a generic type T. something like this.

T value = (T) param;

Here is my example code.

public class App {
  public static void main(String[] args) {
      MyGeneric<Double> myGeneric = new MyGeneric();
      Object obj = myGeneric.getValue("12.45");
  }
}

public class MyGeneric<T> {
  public T getValue(Object value) {
      return (T) value;
  }
}

I have a generic class of type , and a method which receives an Object as parameter and return the same object cast to .

I expect that my class automatically cast from "12.45" to the double value 12.45. However, my class just does nothing. At the end the value in the variable "obj" is still a String.

My question is how to achieve what I want. The reason why I send a string "12.45" to my method getValue() is because that data is not controlled by me. An external application need to use my generic class and for some reason they send a String representation of the value "12.45". So my class could handle integers, floats, double, or anything.

The thing is, a cast cannot actually change the type of an object. It can refer to the object by any of the types that it already belongs to - but it cannot change the actual type.

A String is not a Double , so you cannot cast String to Double . You need to call Double.valueOf() .

You can't cast a String to a Double ; you have to convert the value. Casting means telling the JVM that an object known to be of one supertype is really an object of a subtype, and that's not the case here.

Instead, your code that knows the value is a String and wants it to be a Double needs to use `Double.valueOf(stringVariable).

Just sketchy, but you could use (1) a desired Class, (2) reflection

public static <T> T getValue(Class<T> klazz, Object value) {
    try {
        // Try whether value has correct type:
        return klazz.cast(value);
    } catch (ClassCastException e) {
        // Try whether klazz has static .valueOf(String)

        // Then value not null:
        String s = value.toString();
        Method valueOf = klazz.getDeclaredMethod("valueOf", String.class);
        int modifiers = valueOf.getModifiers();
        if (Modifiers.isStatic(modifiers)) {
            valueOf.setAccessible(true);
            return valueOf.invoke(null, s);
        }
    }
    throw new IllegalArgumentException(value);
}

double x = getValue(Double.class, "12.34");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM