Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
505 views
in Technique[技术] by (71.8m points)

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

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

At run-time, 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 verify if this fruit object is an instance of Apple or Fruit. Both of these 2 expressions return true, which is normal.

But is there a way to determine precisely the declared type of fruit identifier? Which in this case is Fruit.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...