studentoflif...@gmail.com wrote:
Hello all,
a primitive question
I receive an object var which is of the type Object
then to verify its type i write following code
if (var instance of X)
.... do something
if (var instance of Y)
.... do something
if (var instance of Z)
.... do something
if (var instance of J)
.... do something
With Java Generics can i find out the dynamic type of var and typecast
it to its dynamic type, this will save me these unnecessary lines of
code ?
Thanks
Student
Unfortunately, no.
however, if you have a lot of "if instanceof" chains, you probably
should look into making this object polymorphic instead. It'll produce
cleaner code, and let X,Y,Z, and J decide on how they want to handle "do
something"
I agree with you. Unfortunately I am using a library given by some
other team in which I have to check instanceof for 7 different classes
and then call the same getXX() method. i dont know why they didn't
pull this method into the base class.
The only reason i can think of is that in their hierarchy there must
be more than 7 sub classes from the same base class and the other
classes (apart from the 7 having the method) may didn't require the
same getXX() method
thanks
Student