dimanche 24 avril 2016

Is it bad practice to use Object.getClass() in Java?

I am well aware of the fact that reflection should only be used as a last resort, and even if you are in a situation where it seems you should rely on it may imply bad design on your part. It's a very powerful tool that should only be used with extreme caution.

I am also aware that Java stores some housekeeping information about objects, so in theory it should be a relatively cheap operation to determine the dynamic type of an object with Object.getClass() (at least cheap compared to languages without such housekeeping data, for example C++, where expensive vtable lookups are needed for RTTI).

Is this really the case? Is it considered bad practice in Java to check if an object of some base is a certain derived type using getClass()?





Aucun commentaire:

Enregistrer un commentaire