Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of the C# keyword 'as' in Java

Tags:

java

c#

casting

In Java, is it possible to attempt a cast and get back null if the cast fails?

like image 291
shoosh Avatar asked Jun 23 '09 18:06

shoosh


People also ask

What is the C equivalent of a class?

There is nothing equivalent to classes . Its a totally different paradigm. You can use structures in C. Have to code accordingly to make structures do the job.

Is C similar to C+?

C++ is a superset of C, so both languages have similar syntax, code structure, and compilation. Almost all of C's keywords and operators are used in C++ and do the same thing. C and C++ both use the top-down execution flow and allow procedural and functional programming.

Can I use new in C?

There's no new / delete expression in C. The closest equivalent are the malloc and free functions, if you ignore the constructors/destructors and type safety.

What is delete in C?

delete keyword in C++ Delete is an operator that is used to destroy array and non-array(pointer) objects which are created by new expression. Delete can be used by either using Delete operator or Delete [ ] operator. New operator is used for dynamic memory allocation which puts variables on heap memory.


1 Answers

public static <T> T as(Class<T> t, Object o) {   return t.isInstance(o) ? t.cast(o) : null; } 

Usage:

MyType a = as(MyType.class, new MyType());    // 'a' is not null  MyType b = as(MyType.class, "");    // b is null 
like image 61
erickson Avatar answered Sep 23 '22 02:09

erickson