In fact, you are asking about declaring a variable fruit
, not the actual type of the runtime of the object (in this case, Apple
).
I think this is generally a bad idea: you simply declared a variable and told the compiler that it was fruit
, so why do you need to find out now?
To confuse matters even more, itโs worth noting that you can also have several variables with different declared types referring to the same object (which is still Apple):
Fruit fruit = new Apple();
If you really want to know the declared type, you have several options:
- Make
fruit
an instance variable and query for the declared type using reflection. - Do some source code processing to find the variable declaration
- Do some processing of the compiled bytecode to find the type of declaration (although there is a possibility that an aggressive compiler may even completely refuse to declare compilation time, for example, after realizing that the fruit can only be Apple in this code)
I think all this is pretty ugly, so my general advice would be โdon't do thisโ.
source share