25

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

Luka Samkharadze
  • 111
  • 1
  • 12
Anubhav Ranjan
  • 1,558
  • 3
  • 18
  • 32
  • Good question though I think "as" is a truly horrendous pattern - I'd much rather use a cast and get an exception (i.e. a noisy failure you can fix) rather than a silent conversion to null that can bite you at some random point in the future..... and if you genuinely don't know if the cast is going to work or not, you still have to test for null later so you haven't even saved any typing! – mikera Jun 02 '11 at 20:28
  • 3
    You can still cast it like Java's casting. "as" is a deliberate choice by the developer saying "I don't want that casting exception, if it's not the right type I want null" – Hounshell Nov 23 '11 at 21:12

3 Answers3

28

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);
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
22

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

User user = null;
if(obj instanceof User) {
  user = (User) obj;
}
jberg
  • 4,758
  • 2
  • 20
  • 15
  • I think you mean `x instanceof User`, right? – templatetypedef Jun 02 '11 at 20:09
  • yeah, fixed it to match the question – jberg Jun 02 '11 at 20:10
  • 3
    But using instanceof is like using the IS Keyword of C#. – Anubhav Ranjan Jun 02 '11 at 20:11
  • I guess I should have made it more clear, there isn't builtin way to do it. I provided the basic way to get the functionality, some others wrote some more generic versions you can use – jberg Jun 02 '11 at 20:13
  • The problem with this is, it may workout till the type is correct, but as soon as it turns out a mismatch it will throw an exception and will terminate the program. But in case of As keyword, all I have to do is to check for the value to be a null and move further. – Anubhav Ranjan Jun 02 '11 at 20:20
  • This should have the same functionality. If obj is not an instance of User it is currently set to null in the example, otherwise the proper object. You can check for null in this case in the same way – jberg Jun 02 '11 at 20:22
  • @Anubhav - if you're hoping for your program to be maintainable in the future, you *want* to get an exception. Much better to "fail fast" than risk someone forgetting their null checks later and having a stray null value propagate silently around your application..... – mikera Jun 02 '11 at 20:33
  • @mikera Thanks for the point :). Though my intention is different, if I get a null value I will have some other methods of handling them in my code. Let me tell you scenario, suppose I have created a cache using a Dictionary. For every object stored in the dictionary, I have to execute some function. Now in the Dictionary I may have stored different types of objects which needs to be checked and used. I cannot use the key as I will be using the GUID. So the option for me is to use the AS keyword for each of the types present and store the result in different List to call respective methods. – Anubhav Ranjan Jun 02 '11 at 20:57
  • @Anubhav - OK I understand the situation. In that case I'd probably do either something like "if (obj instanceof User) {someFunctionForUser((User)obj);}" or even better extend each of the possible object classes to implement a common interface and do "((MyFunctionInterface)obj).someFunction();" which will then work for any class that implements the interface (thus avoiding a big set of conditional statements). – mikera Jun 02 '11 at 21:10
12

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

pickypg
  • 22,034
  • 5
  • 72
  • 84
trutheality
  • 23,114
  • 6
  • 54
  • 68