So I do not like this for some reason:
((Foo) list.get(0)).getBar();
Is it possible to do something like this:
list.get(0).castTo(Foo.class).getBar();
Thanks.
So I do not like this for some reason:
((Foo) list.get(0)).getBar();
Is it possible to do something like this:
list.get(0).castTo(Foo.class).getBar();
Thanks.
You do have Class.cast(Object obj);
method. But it would be stupid to use instead of the regular way just because you don't happen to like it.
It's also an extra method call instead of a compile-time construct, so they're not directly equivalent to each other.
Not to mention that 6ton
already mentioned in the comments that the example is avoidable with generics...
You can use class.cast(Object)
.
Read Java Class.cast() vs. cast operator.
Foo.class.cast(list.get(0)).getBar();
However, I suggest you to use a variable.
Foo foo = (Foo)list.get(0);
Bar bar = foo.getBar();