Java 中是否有任何类似于 C# 的“AS”关键字的关键字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6219773/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 14:54:56  来源:igfitidea点击:

Is there any keyword in Java which is similar to the 'AS' keyword of C#

c#javakeywordas-keyword

提问by Anubhav Ranjan

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.

正如我们所知,C# 提供了一个 AS 关键字,它会自动检查对象是否属于某种类型,如果是,则将其强制转换为所需的类型,否则返回 null。

public class User

public class User

{

{

}

}

....

....

Object obj = someObj;

Object obj = someObj;

User user = obj As User;

User user = obj As User;

...

...

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.

在上面的示例中,对象 obj 可以是 User 类型或其他类型。用户将获得一个 User 类型的对象或一个 null。这是因为 C# 的 As 关键字首先执行检查,然后在可能的情况下将对象强制转换为结果类型。

So is there any keyword in Java which is equivalent to the AS keyword of C#?

那么Java中是否有与C#的AS关键字等价的关键字呢?

回答by Peter Lawrey

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

回答by jberg

no, you can check with instanceofand then cast if it matches

不,您可以检查instanceof然后投射是否匹配

User user = null;
if(obj instanceof User) {
  user = (User) obj;
}

回答by trutheality

No keyword, but for completeness I'll give you the 1-liner equivalent:

没有关键字,但为了完整起见,我会给你 1-liner 等价物:

User user = obj instanceof User ? (User) obj : null;

(You might not have to have the explicit cast, I'm not sure.)

(您可能不必进行明确的演员表,我不确定。)