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

I have a simple Apple class extending from another simple Fruit class.

At runtime, I could use

Fruit fruit = new Apple(); fruit.getClass(); 

to get the actual type of fruit object, which is Apple.class.

I could also use fruit instanceof Apple and fruit instanceof Fruit to check if this fruit object is an instance of Apple or Fruit. Both of these expressions return true, which is normal.

But is there a way to pinpoint the declared identifier type fruit ? What in this case is fruit .

+6
source share
3 answers

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(); // fruit declared as Fruit, but refers to an Apple Object thing = fruit; // thing declared as Object, refers to the same 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โ€.

+9
source

The Fruit object has no declared type. This is a variable Fruit , which has its own type. Since the only thing you can pass is a reference to the Fruit object, I don't think your request makes sense. The best you could get is to have a specific instance variable in which your object is stored. Then you can flip this field and get its declared type using Field.getType() .

+3
source

No, no: at least not using reflection. Reflection can provide you with information about an object at runtime, as well as fields, methods, and classes, but not local variables. If the fruit was a field, you could do something like the following:

 FruitBasket.class.getDeclaredField("fruit").getType(); 
+3
source

Source: https://habr.com/ru/post/919930/


All Articles