How to check if some class implements interface? When having:
如何检查某些类是否实现了接口?当有:
Character.Gorgon gor = new Character.Gorgon();
Character.Gorgon gor = new Character.Gorgon();
how to check if gor
implements Monster
interface?
如何检查gor是否实现了Monster接口?
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?
方法getLevel()是否正确地在Gorgon中重写,因此它可以返回创建的新gor的级别?
4 个解决方案
#1
180
For an instance
例如
Character.Gorgon gor = new Character.Gorgon();
Then do
然后做
gor instanceof Monster
For a Class instance do
对于Class实例
Class<?> clazz = Character.Gorgon.class;
Monster.class.isAssignableFrom(clazz);
#2
32
Use
使用
if (gor instanceof Monster) {
//...
}
#3
8
In general for AnInterface
and anInstance
of any class:
通常用于任何类的AnInterface和anInstance:
AnInterface.class.isAssignableFrom(anInstance.getClass());
#4
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.
如果你想要一个像public void doSomething([Object implements Serializable])这样的方法,你可以像这个public void doSomething(Serializable serializableObject)一样输入它。您现在可以将任何实现Serializable的对象传递给它,但是使用serializableObject只能访问Serializable接口中对象中实现的方法。
#1
180
For an instance
例如
Character.Gorgon gor = new Character.Gorgon();
Then do
然后做
gor instanceof Monster
For a Class instance do
对于Class实例
Class<?> clazz = Character.Gorgon.class;
Monster.class.isAssignableFrom(clazz);
#2
32
Use
使用
if (gor instanceof Monster) {
//...
}
#3
8
In general for AnInterface
and anInstance
of any class:
通常用于任何类的AnInterface和anInstance:
AnInterface.class.isAssignableFrom(anInstance.getClass());
#4
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.
如果你想要一个像public void doSomething([Object implements Serializable])这样的方法,你可以像这个public void doSomething(Serializable serializableObject)一样输入它。您现在可以将任何实现Serializable的对象传递给它,但是使用serializableObject只能访问Serializable接口中对象中实现的方法。