简体   繁体   English

用Java转换通用类型(例如T值=(T)inputParam)

[英]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进行类型转换。

T value = (T) param; T值=(T)参数;

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 . 我有一个类型的泛型类,和一个接收Object作为参数并返回相同对象的方法。

I expect that my class automatically cast from "12.45" to the double value 12.45. 我希望我的班级自动从“ 12.45”强制转换为双精度值12.45。 However, my class just does nothing. 但是,我的课什么也没做。 At the end the value in the variable "obj" is still a String. 最后,变量“ obj”中的值仍然是字符串。

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. 我向方法getValue()发送字符串“ 12.45”的原因是因为该数据不受我控制。 An external application need to use my generic class and for some reason they send a String representation of the value "12.45". 外部应用程序需要使用我的通用类,并且由于某些原因,它们发送值“ 12.45”的String表示形式。 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 . String不是Double ,因此不能将StringDouble You need to call Double.valueOf() . 您需要调用Double.valueOf()

You can't cast a String to a Double ; 您不能 String转换为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. 强制转换的意思是告诉JVM,一个已知属于一个超类型的对象实际上是一个子类型的对象,而事实并非如此。

Instead, your code that knows the value is a String and wants it to be a Double needs to use `Double.valueOf(stringVariable). 相反,知道该值是String并希望将其作为Double需要使用Double.valueOf(stringVariable)。

Just sketchy, but you could use (1) a desired Class, (2) reflection 只是粗略的,但是您可以使用(1)所需的Class,(2)反射

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Java泛型和数组类型,不是你想的(例如来自泛型类型的数组) - Java generic and array types, no not what you are thinking (e.g. arrays from generic types) 用于泛型类型的Java转换“.class”-operator,例如列表,到“Class <List <?>>”和“Class <List <Integer >>” - Java casting “.class”-operator used on a generic type, e.g. List, to “Class<List<?>>” and to “Class<List<Integer>>” Java - 为什么在递归调用中不维护原始包装类(例如Integer)的值? - Java - Why value of primitive wrapper class (e.g. Integer) isn't maintained in recursive calls? 返回Java中通用对象(例如列表)的更干净的解决方案 - Cleaner solution to returning generic objects (e.g. Lists) in Java 用Java转换通用类型 - Casting generic types in Java 如何检查数组的所有元素是否不等于某个值? (例如,不是空的) - How can I check if all elements of array doesn't equal to some value? (e.g. not empty) 有没有办法使用 skyve 验证器(例如电子邮件)来测试不是 bean 属性的值? - Is there a way to use a skyve validator (e.g. email) to test a value which isn't an attribute on a bean? 使用指定的类型创建集合(例如Map) - 不使用通用Object类 - Create Collection (e.g. Map) with specified Types - not using generic Object class Java中有没有一种方法可以基于java.lang基本类型(例如String)构建自定义类型? - Is there a way in Java to build custom types based on java.lang base Types (e.g. String)? 在循环Java 7中转换泛型类型 - Casting Generic types in loops Java 7
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM