如何在Java中模拟C#as-operator [英] How to emulate C# as-operator in Java
本文介绍了如何在Java中模拟C#as-operator的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在某些情况下,使用类型转换返回一个空值是很实际的,而不是抛出一个ClassCastException。 C#有作为
运算符来执行此操作。在Java中有一些等价的东西,所以你不必显式检查ClassCastException?
There are situations, where it is practical to have a type-cast return a null value instead of throwing a ClassCastException. C# has the as
operator to do this. Is there something equivalent available in Java so you don't have to explicitly check for the ClassCastException?
推荐答案
,如@Omar Kooheji所建议:
Here's an implementation of as, as suggested by @Omar Kooheji:
public static <T> T as(Class<T> clazz, Object o){
if(clazz.isInstance(o)){
return clazz.cast(o);
}
return null;
}
as(A.class, new Object()) --> null
as(B.class, new B()) --> B
这篇关于如何在Java中模拟C#as-operator的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文