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

倖福魔咒の 提交于 2019-12-30 03:48:27

问题


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.

public class User

{

}

....

Object obj = someObj;

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.

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


回答1:


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



回答2:


no, you can check with instanceof and then cast if it matches

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



回答3:


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

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

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



来源:https://stackoverflow.com/questions/6219773/is-there-any-keyword-in-java-which-is-similar-to-the-as-keyword-of-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!