Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to emulate C# as-operator in Java

Tags:

java

casting

There are situations, where it is practical to have a type-cast return a null value instead of throwing a ClassCastException. C# has the as operator to do this. Is there something equivalent available in Java so you don't have to explicitly check for the ClassCastException?

like image 221
VoidPointer Avatar asked Sep 29 '08 14:09

VoidPointer


People also ask

What programming language are emulators written in?

You'll need a working knowledge of C, and a knowledge of assembly language might be helpful. If you don't know assembly, writing an emulator is a great way to become knowlegeable about it. You will also need to be comfortable with hexadecimal math (also known as base 16, or simply "hex").

How hard is it to write an emulator?

Writing emulators is hard because you must exactly/completely/absolutely replicate said hardware behaviour, including it's OS behaviour in software. Writing emulators for older consoles was in some cases harder than writing emulators for modern consoles.


2 Answers

Here's an implementation of as, as suggested by @Omar Kooheji:

public static <T> T as(Class<T> clazz, Object o){     if(clazz.isInstance(o)){         return clazz.cast(o);     }     return null; }  as(A.class, new Object()) --> null as(B.class, new B())  --> B 
like image 122
Aaron Maenpaa Avatar answered Sep 29 '22 16:09

Aaron Maenpaa


I'd think you'd have to roll your own:

return (x instanceof Foo) ? (Foo) x : null; 

EDIT: If you don't want your client code to deal with nulls, then you can introduce a Null Object

interface Foo {     public void doBar(); } class NullFoo implements Foo {     public void doBar() {} // do nothing } class FooUtils {     public static Foo asFoo(Object o) {         return (o instanceof Foo) ? (Foo) o : new NullFoo();     } } class Client {     public void process() {         Object o = ...;         Foo foo = FooUtils.asFoo(o);         foo.doBar(); // don't need to check for null in client     } } 
like image 28
toolkit Avatar answered Sep 29 '22 17:09

toolkit