How to check if an object implements an interface?
If you want a method like public void doSomething([Object implements Serializable])
you can just type it like this public void doSomething(Serializable serializableObject)
. You can now pass it any object that implements Serializable but using the serializableObject
you only have access to the methods implemented in the object from the Serializable interface.
For an instance
Character.Gorgon gor = new Character.Gorgon();
Then do
gor instanceof Monster
For a Class instance do
Class<?> clazz = Character.Gorgon.class;
Monster.class.isAssignableFrom(clazz);
In general for AnInterface
and anInstance
of any class:
AnInterface.class.isAssignableFrom(anInstance.getClass());
Use
if (gor instanceof Monster) {
//...
}