How to check if an object implements an interface?

JavaOopInterface

Java Problem Overview


How to check if some class implements interface? When having:

Character.Gorgon gor = new Character.Gorgon();

how to check if gor implements Monster interface?

public interface Monster {
    
    public int getLevel();
    
    public int level = 1;
}

public class Character {
    public static class Gorgon extends Character implements Monster {
        public int level;
        @Override
        public int getLevel() { return level; }
        
		public Gorgon() {
			type = "Gorgon";
		}
    }
}

Is the method getLevel() overridden in Gorgon correctly, so it can return level of new gor created?

Java Solutions


Solution 1 - Java

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);

Solution 2 - Java

Use

if (gor instanceof Monster) {
    //...
}

Solution 3 - Java

In general for AnInterface and anInstance of any class:

AnInterface.class.isAssignableFrom(anInstance.getClass());

Solution 4 - Java

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJ.OlufsenView Question on Stackoverflow
Solution 1 - JavaMike QView Answer on Stackoverflow
Solution 2 - JavakrockView Answer on Stackoverflow
Solution 3 - JavaOleg MikhailovView Answer on Stackoverflow
Solution 4 - JavaBananyaDevView Answer on Stackoverflow