Skip to content
Advertisement

Print the type name of object held by variable

In Java, is it possible to print the type of value held by variable?

JavaScript

One approach to this problem would be to use an if-statement for each variable type, but that would seem redundant, so I’m wondering if there’s a better way to do this:

JavaScript

Advertisement

Answer

I am assuming that in case of Animal myPet = new Cat(); you want to get Cat not Animal nor myPet.

To get only name without package part use

JavaScript

otherwise

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement