class - How to find out the declared type of an identifier in Java? -


i have simple class apple extends simple class fruit.

at run-time, use

fruit fruit = new apple(); fruit.getclass(); 

to actual type of fruit object, apple.class.

i use fruit instanceof apple, , fruit instanceof fruit verify if fruit object instance of apple or fruit. both of these 2 expressions return true, normal.

but there way determine precisely declared type of fruit identifier? in case fruit.

you're asking question variable declaration of fruit rather actual runtime type of object (which apple in case).

i think in general bad idea: declared variable , told compiler fruit, why need need find out?

just confuse matters more, it's worth noting can have multiple variables different declared types referencing same object (which still apple):

fruit fruit = new apple(); // fruit declared fruit, refers apple object thing = fruit; // thing declared object, refers same apple 

if want find out declared type, have few options:

  • make fruit instance variable, , query declared type using reflection.
  • do processing of source code find variable declaration
  • do processing of compiled bytecode find declaration type (although there possibility aggressive compiler might optimise compile time declaration away altogether, e.g. after realising fruit can ever apple in code)

i think of these pretty ugly, general advice "don't it".


Comments

Popular posts from this blog

javascript - backbone.js Collection.add() doesn't `construct` (`initialize`) an object -

php - Get uncommon values from two or more arrays -

Adding duplicate array rows in Php -