Java instanceof with changing objects

[亡魂溺海] 提交于 2020-01-12 11:39:03

问题


I need a method where i could pass on a parameter which i assume would be a Class (not sure though) and in that method, instanceof would be used to check if x is an instance of the passed Class.

How should i do that? I tried a few things but none worked.


回答1:


How about this:

public boolean checker(Object obj) {
    return obj instanceof SomeClass;
}

or if SomeClass is a parameter:

public boolean checker(Object obj, Class someClass) {
    return someClass.isInstance(obj);
}

or if you want the instance to be someClass and NOT an instance of a subclass of someClass:

public boolean checker(Object obj, Class someClass) {
    return someClass.equals(obj.getClass());
}



回答2:


Use Class.isInstance(Object).



来源:https://stackoverflow.com/questions/12766233/java-instanceof-with-changing-objects

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