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?
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").
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.
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
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 } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With