如何在Java中找出标识符的声明类型? [英] How to find out the declared type of an identifier in Java?
问题描述
我有一个简单的类从另一个简单的类Fruit扩展。
I have a simple class Apple extends from another simple class Fruit.
在运行时,我可以使用
Fruit fruit = new Apple();
fruit.getClass();
获取水果对象的实际类型,即Apple.class。
to get the actual type of fruit object, which is Apple.class.
我还可以使用水果实例的Apple
和水果实例
来验证这个水果对象是苹果或水果的一个实例。这两个表达式都返回true,这是正常的。
I could also use fruit instanceof Apple
, and fruit instanceof Fruit
to verify if this fruit object is an instance of Apple or Fruit. Both of these 2 expressions return true, which is normal.
但是有一种方法可以精确地确定 fruit
identifier?在这种情况下是水果
。
But is there a way to determine precisely the declared type of fruit
identifier? Which in this case is Fruit
.
推荐答案
一个关于 fruit
的变量声明的问题,而不是对象的实际运行时类型(这是 Apple
案件)。
You're actually asking a question about the variable declaration of fruit
rather than the actual runtime type of the object (which is an Apple
in this case).
我认为这是一个坏主意:你只是声明了变量,告诉编译器它是一个水果$ c $
I think this is in general a bad idea: you just declared the variable and told the compiler that it is a Fruit
, so why do you need to now need to find this out?
为了更多地混淆事情,值得注意的是,你也可以有多个变量与不同的声明的类型引用同一个对象(它仍然是一个苹果):
Just to confuse matters even more, it's worth noting that you can also have multiple variables with different declared types referencing the same object (which is still an 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 declared type, then you have a few options:
- 使
fruit
- 对源代码进行一些处理以找到变量声明
- 对编译的字节码进行一些处理找到声明类型(虽然积极的编译器可能甚至优化编译时声明,例如在意识到水果只能在这个代码中是一个苹果)。
我认为所有这些都是很丑陋的,所以我的一般建议是不要做。
I think all of these are pretty ugly, so my general advice would be "don't do it".
这篇关于如何在Java中找出标识符的声明类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!