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

感情迁移 提交于 2019-12-03 10:57:05

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

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

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

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

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