Yes, there are a few ways to do this. One is to use the getClass()
method. Because this is defined in the Object
class, it can be called on every Java object.
System.out.println(myObject.getClass());
or even
if (myObject.getClass() == MyClass.class)
But if you only want to know whether an object is an instance of a particular class, you can write
if (myObject instanceof MyType)
which will return true
if the class of myObject
is MyType
or any subtype thereof. You can use either an interface or a class for MyType
here - even an abstract class.
However, as Tim pointed out in the comments, often there are better ways to design your program than relying on one of these ways of checking the class of an object. Careful use of polymorphism reduces the need for either of these.