1

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.

Koray Tugay
  • 22,894
  • 45
  • 188
  • 319
  • 2
    Why do you not like the first (other than the problem that the precedence is always making you wonder about adding extra `()`)? – Hot Licks Aug 04 '14 at 17:09
  • @HotLicks I think it breaks the view and slows down typing a lot. – Koray Tugay Aug 04 '14 at 17:10
  • There is no dynamic cast mechanism, if that's what you're wondering. – Hot Licks Aug 04 '14 at 17:10
  • Yeah, the cast syntax inherited from C sucks for several reasons. But it's far from the only wart on the language. – Hot Licks Aug 04 '14 at 17:11
  • @HotLicks I am a beginner so this kind of caught my eye. The others I would not know really. – Koray Tugay Aug 04 '14 at 17:11
  • 2
    May not be applicable for a broader context, but at least in this example you can avoid casting by generics – 6ton Aug 04 '14 at 17:12
  • Just consider it a minor wart. It's that way for historical reasons, and it's not going to change, so we live with it. Just be thankful you're not dealing with C strings and arrays. – Hot Licks Aug 04 '14 at 17:13
  • Do understand that if you use one of the suggested "alternatives" then others (including your instructor) will have trouble reading your code and will consider it to have non-standard "standards". – Hot Licks Aug 04 '14 at 17:15

2 Answers2

3

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

Kayaman
  • 72,141
  • 5
  • 83
  • 121
2

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();
Community
  • 1
  • 1
spongebob
  • 8,370
  • 15
  • 50
  • 83