Reputation: 983
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
.
Upvotes: 8
Views: 3961
Reputation: 106401
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:
fruit
an instance variable, and query the declared type using reflection.I think all of these are pretty ugly, so my general advice would be "don't do it".
Upvotes: 14
Reputation: 10245
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();
Upvotes: 3
Reputation: 200246
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()
.
Upvotes: 3