dynamic type

S

studentoflife77

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
 
D

Daniel Pitts

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"
 
S

studentoflife77

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
 
D

Daniel Pitts

(e-mail address removed) wrote:
[some top posted reply, fixed below]
Please don't top post.
My suggestion is to ask the other team to add that method to a base
class or at least to an interface. If you can't the other team to make
changes, than they aren't your friends :)

If you are feeling particularly proactive, you might even suggest to the
other team that you can make the change yourself.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,430
Messages
2,571,676
Members
48,796
Latest member
Greg L.

Latest Threads

Top