简体   繁体   English

Java强制转换方法

[英]Java cast method

I am not sure if this question belongs here. 我不确定这个问题是否属于这里。 I have written the following method to cast an object to a particular type. 我编写了以下方法将对象强制转换为特定类型。

private static <T> T cast(Object obj) {
    return (T) (obj);
}

I am wondering why I do not find such method in Guava or Apache Commons? 我想知道为什么我在Guava或Apache Commons中找不到这样的方法? Am I missing something? 我错过了什么吗?

Thanks, 谢谢,

Venk Venk

You can use standart cast method with method 你可以用方法使用标准施法

SomeClass o = SomeClass.class.cast(obj);  

No reason to use your method 没理由使用你的方法

SomeClass o = Utils.<SomeClass>cast(obj);

Because it is not typesave. 因为它不是typesave。 Guava in particular is designed to utilize javas static typing to the maximum. 特别是Guava旨在最大限度地利用javas静态类型。 With your method it would be possible to cast an object of any class to an object of any other class. 使用您的方法,可以将任何类的对象强制转换为任何其他类的对象。 This is not supposed to be done. 这不应该做。

if you would try the following 如果你想尝试以下

Integer a = (Integer) "1";

the compiler would rightfully complain. 编译器会理所当然地抱怨。 If you'd use your cast method you would just get rid of the compilation error and postpone the error to runtime. 如果你使用你的强制转换方法,你只需要摆脱编译错误并将错误推迟到运行时。 Which is never a good idea. 这绝不是一个好主意。 Additionally the compiler warns you that the cast to T is unchecked and may cause problems later on. 此外,编译器会警告您未选中对T的强制转换,以后可能会导致问题。

In most cases the java type inference is pretty solid and you should listen to compiler warnings. 在大多数情况下,java类型推断非常可靠,您应该听编译器警告。

Reflection on the other hand discards the java type systeme nearly completely. 另一方面,反射几乎完全抛弃了java类型系统。 Dealing with this is a little tricky but there are ways to check if types are compatible (eg. Class.isAssignableFrom(Class) ). 处理这个有点棘手,但有办法检查类型是否兼容(例如Class.isAssignableFrom(Class) )。

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

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