Koray Tugay
Koray Tugay

Reputation: 23780

Can I make class cast in Java using methods?

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.

Upvotes: 1

Views: 87

Answers (2)

user3453226
user3453226

Reputation:

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();

Upvotes: 2

Kayaman
Kayaman

Reputation: 73538

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

Upvotes: 3

Related Questions