Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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#?

like image 984
Anubhav Ranjan Avatar asked Jun 02 '11 20:06

Anubhav Ranjan


People also ask

Is static in C same in Java?

The concept of static in Java doesn't adhere with the concept of static in C. However, there is a static keyword in Java as well. But its more like a static in C++ then C, with some differences.

Is there any this keyword in Java?

The this keyword refers to the current object in a method or constructor. The most common use of the this keyword is to eliminate the confusion between class attributes and parameters with the same name (because a class attribute is shadowed by a method or constructor parameter).

How many keywords are there in C and Java?

Because of this, programmers cannot use keywords in some contexts, such as names for variables, methods, classes, or as any other identifier. Of these 67 keywords, 16 of them are only contextually reserved, and can sometimes be used as an identifier, unlike standard reserved words.


2 Answers

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); 
like image 107
Peter Lawrey Avatar answered Oct 29 '22 22:10

Peter Lawrey


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

User user = null; if(obj instanceof User) {   user = (User) obj; } 
like image 35
jberg Avatar answered Oct 29 '22 21:10

jberg