有没有在Java中任何关键字它类似于C#的“AS”关键字 [英] Is there any keyword in Java which is similar to the 'AS' keyword of C#
问题描述
我们知道C#提供了一个AS关键字自动执行检查对象是否是一个类型的,如果是,它那么它投射到别人所需要的类型给出了一个空。
As we know C# provides an AS keyword which automatically performs a check whether the Object is of a type and if it is, it then casts it to the needed type else gives a null.
公共类用户
{
}
...
obj对象= someObj中;
用户的用户= OBJ时用户;
...
在这里,在上述例子中,
的对象物obj的类型可以是用户或一些其他类型。
中的用户将或者获得式用户或空的一个目的。
这是因为,C#的作为关键字首先进行检查,如果可能的话,然后进行对象向所得类型的铸造
Here in the above example, An Object obj can be of type User or some other type. The user will either get an object of type User or a null. This is because the As keyword of C# first performs a check and if possible then performs a casting of the object to the resulting type.
那么,有任何关键字在Java中相当于C#的AS关键字?
So is there any keyword in Java which is equivalent to the AS keyword of C#?
推荐答案
您可以创建一个helper方法
You can create a helper method
public static T as(Object o, Class<T> tClass) {
return tClass.isInstance(o) ? (T) o : null;
}
User user = as(obj, User.class);
这篇关于有没有在Java中任何关键字它类似于C#的“AS”关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!