150

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?

vbence
  • 20,084
  • 9
  • 69
  • 118
J.Olufsen
  • 13,415
  • 44
  • 120
  • 185

4 Answers4

250

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);
Mike Q
  • 22,839
  • 20
  • 87
  • 129
46

Use

if (gor instanceof Monster) {
    //...
}
krock
  • 28,904
  • 13
  • 79
  • 85
35

In general for AnInterface and anInstance of any class:

AnInterface.class.isAssignableFrom(anInstance.getClass());
Oleg Mikhailov
  • 5,751
  • 4
  • 46
  • 54
1

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.

BananyaDev
  • 583
  • 5
  • 13