Java 7 suggestion: if-instanceof

Coding Java today I figured one really small and neat feature to make Java easier. Don’t really know how to call it – may be “if-instanceof”.

Here is comes:

Sometimes you have to actually check if an object is of specific class and take some extra action. I know that OOP people will say it is a bad practice or something like that, but in reality there is instanceof operator and people use it. So you write something like this:


Shape object;
if (object instanceof Rectangle)
{
     Rectangle rect = (Rectangle) object;
     doSomethingOnRectangle(rect);
}

Here we have really annoying piece of code Rectangle rect = (Rectangle) object;. Why do you have to write it? In scope of the if ( .. instanceof ..) we know the object is a Rectangle. So it would be really nice if Java was smart enough to use checked type in scope of the if. That would save us some time casting and introducing another variable.

Shape object;

if (object instanceof Rectangle)
{
    doSomethingOnRectangle(object); // here object is passed as Rectangle
}

That’s it. Simple.

Tags: , , , ,

Leave a Reply