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

2022-09-01 20:01:24

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 and then cast if it matchesinstanceof

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