Java:从X到Y的未选中强制转换/如何实现castOrNull [英] Java: Unchecked cast from X to Y / how to implement castOrNull
问题描述
我已实现此功能:
static <X,Y> Y castOrNull(X obj) {
try {
return (Y)obj;
}
catch(ClassCastException e) {
return null;
}
}
这给我编译器警告:
Type safety: Unchecked cast from X to Y
这我不太明白。不是 try / catch
我在这里做一个检查吗?我可以忽略这个警告吗?
Which I don't exactly understand. Isn't the try/catch
which I am doing here a check for it? Can I ignore the warning?
我的函数能否正常工作?我如何正确实现它?
Will my function work as expected or not? How would I implement it correctly?
我也尝试过一个 obj instanceof Y
检查,但是不工作因为Java处理泛型的方式。
I also tried with a obj instanceof Y
check but that doesn't work because of the way Java handle generics.
Btw。,这个函数对我来说很有用(让一些其他代码更干净)。我不知道这样的函数在Java中是否已经存在?
Btw., this function seems quite useful to me (to make some other code more clean). I wonder if such a function may already exist in Java?
我想使用它的一个例子:
One example where I want to use it:
void removeEmptyRawStrings() {
for(Iterator<Entity> e = entities.iterator(); e.hasNext();) {
RawString s = castOrNull(e.next());
if(s != null && s.content.isEmpty()) e.remove();
}
}
我在我的代码中经常遇到这样的情况。我认为这是比其他任何东西更可读和更简单。但是如果你有任何关于如何让代码更简单的话,请给我一个更好的建议。
I have cases like these quite often in my code. And I think this is more readable and simpler than anything else. But please give me a better suggestion if you have any about how to make that code even more simple.
推荐答案
是用于动态铸造的通用参数 Y
被视为 Object
。它永远不会抛出CCE。
So the problem here is that the generic parameter Y
when used for dynamic casting is treated as Object
. It will never throw a CCE. You get a CCE thrown in the calling method, as you have broken static type safety.
还有 X code>在这里是完全没有意义的:
Also X
is entirely pointless here:
几乎肯定正确的解决方案不是尝试这样的。 null
是错误的。
Almost certainly the correct solution is not to attempt anything like this. null
is bad. Casting is bad.
但是,如果你决定写废话,可以传递 Class
对象:/ p>
However, if you are determined to write nonsense, you can pass the Class
object:
public static <T> T evilMethod(Class<T> clazz, Object obj) {
try {
return clazz.cast(obj);
} catch (ClassCastException exc) {
return null;
}
}
这篇关于Java:从X到Y的未选中强制转换/如何实现castOrNull的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!