Link Details

Link 144007 thumbnail
User 328248 avatar

By ksuha
via 99translations.com
Published: Dec 26 2008 / 02:01

Little Java 7 feature suggestion I came up today - I think it is pretty neat.
  • 7
  • 25
  • 3585
  • 1104

Comments

Add your comment
User 241974 avatar

dkharlamov replied ago:

0 votes Vote down Vote up Reply

It's not very obvious. Object casting inside the {} (even in case of instance of) can confuse. Such magic in code makes it easy to read but not understand IMHO

User 254431 avatar

joojoo joojoo replied ago:

0 votes Vote down Vote up Reply

This code might confuse a developer. He/She might end up wondering how a method that accepts rectangles can now accommodate a Shape object, which happens to be a super type.

User 211643 avatar

zynasis replied ago:

0 votes Vote down Vote up Reply

sure it COULD be confusing because it is just another thing to consider when reading code (auto type casting from if)., but i think in the end it will be very benefitial once everyone is used to it

User 60219 avatar

Mikael Grev replied ago:

0 votes Vote down Vote up Reply

If anything, with(object as Rectangle) {} or similar might be used. Or for (..). Questionable if the gains would outweigh the costs though.

User 272422 avatar

htowninsomniac replied ago:

0 votes Vote down Vote up Reply

The nullness checker from JSR 308 already does a similar kind of type refinement in if-statements. I'd like to see a prototype of this.

User 153370 avatar

ronaldtm replied ago:

2 votes Vote down Vote up Reply

It's broken. If 'object' is changed by multiple threads, another thread may change its value after the 'if' statement passed true, causing a ClassCastException.

This happens because you are trying to do a runtime checking (the value of the variable at that exact moment) using a compiler trick, which is a build-time check. This is different from, say, generics, 'cause generics, when used correctly (no warnings, no 'ignore me' annotations) guarantee that the variable will NEVER be assigned with an invalid value. This instanceof compiler trick doesn't do anything but do a cast for you, with all risks of a manual cast.

User 328248 avatar

ksuha replied ago:

0 votes Vote down Vote up Reply

That is very good point, Ronald. I take my idea back.

User 211643 avatar

zynasis replied ago:

0 votes Vote down Vote up Reply

good call mate

User 328248 avatar

ksuha replied ago:

0 votes Vote down Vote up Reply

Right, you have to be genius to understand instanceof.

Add your comment


Html tags not supported. Reply is editable for 5 minutes. Use [code lang="java|ruby|sql|css|xml"][/code] to post code snippets.