Using instanceof with a class Object [duplicate]

久未见 提交于 2020-01-30 13:08:07

问题


What's the correct syntax to make this work?

public boolean isTypeOf(Class type) {
     return this instanceof type;
}

I intend to call it with:

foo.isTypeOf(MyClass.class);

The method will be overriden, otherwise I would just use instanceof inplace.


回答1:


Use Class.isInstance(obj):

public boolean isTypeOf(Class type) {
     return type.isInstance(this);
}

This method determines if the given parameter is an instance of the class. This method will also work if the object is a sub-class of the class.

Quoting from the Javadoc:

This method is the dynamic equivalent of the Java language instanceof operator.



来源:https://stackoverflow.com/questions/32696912/using-instanceof-with-a-class-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!