How do I find the declared identifier type in Java?

I have a simple class Apple extended from another simple class fruit

At runtime, I can use

Fruit fruit = new Apple();

fruit.getClass();

Gets the fruit object of the actual type, i.e. apple class.

I can also use Apple's fruit instanceof and fruit's fruit of to verify whether the fruit object is an instance of apple or fruit Both expressions return true, which is normal

But is there any way to determine the declaration type of fruit Identifier? In this case, fruit

Solution

You're actually asking about the fruit variable declaration, not the actual runtime type of the object (in this case Apple)

I think this is usually a bad idea: you just declared the variable and told the compiler that it was a fruit, so why do you need to find it now?

Just to make things more confusing, it is worth noting that you can also use multiple variables that refer to different declaration types of the same object (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 find out the type of declaration, you have several options:

>Make the fruit an instance variable and use the type declared by the reflection query. > Some processing of source code to find variable declarations > some processing of compiled bytecode to find declaration types (although it is possible that an active compiler may even fully optimize compile time declarations, for example, after recognizing that fruit can only be apple in this code)

I think all this is very ugly, so my general advice is "don't do this"

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>