Java: How should look an instanceof method

孤街醉人 提交于 2019-12-12 18:29:10

问题


Imagine, I want to write a useless method called: isInstanceof that returns a boolean.
I was thinking about it. But I do not get out. An instanceof has to be used like:

[object] instanceof [a classname]

// I was thinking about something like this
public static boolean isInstanceof(Object obj, /*magic for the second param*/)
{
   return obj instanceof /*the magical second param*/
}

But how can I make an parameter for [a classname]? Is there a way to do this without the method isInstance(Class cls) from java.lang.Class?

Thanks


回答1:


Hehe, yes. Use isAssignableFrom(Class) from Class. Not only is it not isInstance(Class), it also matches the way the instanceof operator works more closely. :)

Other than that, no, there’s not much you can do without those methods from Class.




回答2:


A dynamic version of

[object] instanceof [a classname] 

would be:

Class.forName("a classname").isAssignableFrom(object.getClass());


来源:https://stackoverflow.com/questions/1920284/java-how-should-look-an-instanceof-method

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