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

安稳与你 提交于 2019-11-29 13:45:25

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).

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:

  • Make fruit an instance variable, and query the declared type using reflection.
  • Do some processing of the source code to find the variable declaration
  • Do some processing of the compiled bytecode to find the declaration type (although there is a possibility that an aggressive compiler might even optimise the compile time declaration away altogether, e.g. after realising that fruit can only ever be an Apple in this code)

I think all of these are pretty ugly, so my general advice would be "don't do it".

The Fruit object doesn't have a declared type. It's the variable fruit that has its type. Since the only thing you can pass around is a reference to the Fruit object, I don't think your request makes much sense. The best you could get is if you had a specific instance variable where your object is stored. You could then reflect on that field and get its declared type with Field.getType().

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

FruitBasket.class.getDeclaredField("fruit").getType();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!